Proposed Improvements
See original GitHub issueCurrent Code
export default function useForceUpdate(): () => void {
const [ , dispatch ] = useState<{}>(Object.create(null));
// Turn dispatch(required_parameter) into dispatch().
const memoizedDispatch = useCallback(
(): void => {
dispatch(Object.create(null));
},
[ dispatch ],
);
return memoizedDispatch;
}
Proposed Improvements
JS, but can easily be typed:
import { useRef, useState } from 'react';
// Creates an empty object, but one that doesn't inherent from Object.prototype
const newValue = () => Object.create(null);
export default () => {
const setState = useState(newValue())[1];
const forceUpdate = useRef(() => {
setState(newValue());
}).current;
return forceUpdate;
};
Rational:
First, dispatch
unclear. Looking at the history, it is a residue from when useReducer
was used, but this is no longer the case.
Then, from the docs (see note):
React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
So there’s no need providing it as a useCallback
dependency.
Either useCallback
or useMemo
with empty dependencies ([]
- ie, one-off) is identical to useRef().current
which somehow communicates the intent better - this value will not change. Also, with useRef
, react doesn’t call Object.is(old, new) each render.
Also note that in the current code we have memoizedDispatch
but because dispatch
is stable, there’s no real memoization going on - useCallback
will always return the same function.
Finally, in my case, initial render could trigger dozens of forceUpdates
so a further improvement could be (I’m not actually using it because the trade-off doesn’t seem to be worth it, but others may find this useful):
import { useRef, useState, useEffect } from 'react';
// Creates an empty object, but one that doesn't inherent from Object.prototype
const newValue = () => Object.create(null);
export default () => {
const setState = useState(newValue())[1];
const updatePending = useRef(false);
const forceUpdate = useRef(() => {
if (!updatePending.current) {
setState(newValue());
updatePending.current = true;
}
}).current;
useEffect(() => {
updatePending.current = false;
});
return forceUpdate;
};
Issue Analytics
- State:
- Created 4 years ago
- Comments:12 (6 by maintainers)
@evoyy Symbol has poor browser support. As much as I dislike IE, I wouldn’t want to cut out its users from all dependents on this package.
This was the original implementation in this package, and it was requested to be changed so as not to have to deal with max integer values in [primarily older] browsers with a cap.