React hook(s) for safely force-updating components
npm install use-safe-force-update





---
functionReact hook for force-updating a component.
Kind: global function
Returns: function -
Function that forces an update of the component.
jsx
function Component() {
const values = useRef({ number: 0 });
const forceUpdate = useForceUpdate(); const increaseNumber = useCallback(() => {
values.current.number++;
forceUpdate();
}, [values, forceUpdate]);
return (
<>
useMountedForceUpdate() ⇒ function
React hook for force-updating a component only when mounted
(and queuing an update for when the component is mounted.)
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
`js
Force-updates the component immediately after being mounted./caption>
function Component() {
const forceUpdate = useMountedForceUpdate(); React.useMemo(() => {
forceUpdate();
}, []);
}
`
useSafeForceUpdate() ⇒ function
React hook for force-updating a component only when it is mounted.
Note: For React 18+ users, this will not be any different from useForceUpdate, since
there is no warning about setState on unmounted components.
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.)
`js
function Component() {
const forceUpdate = useSafeForceUpdate(); React.useMemo(() => {
setTimeout(() => {
forceUpdate() // React will not ever complain about this!
}, [1000 + Math.random() * 9000])
}, [])
}
``- Ludvig Aldén @ludvigalden
---