Here are the primary methods available to force a component to re-render when using React hooks:
Using useState:
When the state is updated using the useState hook, React automatically triggers a re-render.
Even if you set the same value, React will re-render the component.
const [state, setState] = useState(0);
const forceReRender = () => {
setState(prevState => prevState + 1); // Trigger re-render by updating state
};
Using useReducer:
A custom hook useReducer can also be used to trigger a re-render by dispatching an action.
The reducer function doesn't need to change the state value; it can be used just to increment the state to trigger re-renders.
const [, forceUpdate] = useReducer(x => x + 1, 0); // Force re-render
Changing the key Prop of a Component:
Changing the key prop forces React to treat the component as a completely new one and triggers a re-render.
const [key, setKey] = useState(0);
const forceReRender = () => {
setKey(prevKey => prevKey + 1); // Changing key forces re-render
};
Custom Hook for Forcing Re-render:
You can create a custom hook that uses useState or useReducer to trigger a re-render manually.
function useForceUpdate() {
const [, setTick] = useState(0);
return () => setTick(tick => tick + 1); // Trigger re-render by updating state
}
Related Question : Force React component rerender without setState