I am using forceUpdate
hook like
export const App = ()=>{
const forceUpdate1 = useForceUpdate1();
const forceUpdate2 = useForceUpdate2();
// ignore usage in effect. As both will be used exactly at same place still shows different result
useEffect(() => {
/// some logic
forceUpdate1(); //not working
// forceUpdate2(); //working
},[])
return <>...</>;
}
export const useForceUpdate1 = () => {
const [counter, setCounter] = React.useState(1);
return () => {
setCounter(counter + 1);
}
}
export const useForceUpdate2 = () => {
const [_, forceUpdate] = useReducer((x) => x + 1, 0);
return forceUpdate;
}
Problem
useForceUpdate1()
did not re-render.useForceUpdate2()
was working and caused re-rendering.
I think when forceUpdate1
is called multiple times quickly, it will make state changes only once. I mean if counter = 10
, then calling force update 2
times sequentially will set counter
to 11
and not 12
. But counter value is no use to us as state should still trigger a change and <App>
should be re rendered.
- Is this because of variable capturing?
- How to avoid this confusion in future.