use-safe-force-update
v2.0.0
Published
React hook(s) for safely force-updating components
Downloads
15
Maintainers
Readme
useForceUpdate() ⇒ function
Kind: global function
Returns: function - Function that forces an update of the component.
Example
function Component() {
const values = useRef({ number: 0 });
const forceUpdate = useForceUpdate();
const increaseNumber = useCallback(() => {
values.current.number++;
forceUpdate();
}, [values, forceUpdate]);
return (
<>
<label children={`Increase (currently ${values.current.number})`} for='bth' />
<button onClick={increaseNumber} id='btn' />
</>
)
}
useMountedForceUpdate() ⇒ function
Kind: global function
Returns: function - Function that attempts to force an update of the component. It also allows for queueing an update
for when the component has been mounted, which is simply done by calling the function
before the component has been mounted.
Example
<caption>Force-updates the component immediately after being mounted./caption>
function Component() {
const forceUpdate = useMountedForceUpdate();
React.useMemo(() => {
forceUpdate();
}, []);
}
useSafeForceUpdate() ⇒ function
Kind: global function
Returns: function - Function that attempts to force an update of the component.
Example (Forces an update after 1-10 seconds, which React will never complain about.)
function Component() {
const forceUpdate = useSafeForceUpdate();
React.useMemo(() => {
setTimeout(() => {
forceUpdate() // React will not ever complain about this!
}, [1000 + Math.random() * 9000])
}, [])
}
Authors
- Ludvig Aldén @ludvigalden