0

Currently, I want to forceUpdate function component, I work around and find one way

 function useForceUpdate() {
  const [, setValue] = useState(0); // integer state
  return () => setValue(value => value + 1); // update the state to force render
}
const forceUpdate = useForceUpdate();

and I use it inside useEffect() hook

 useEffect(() => {
    forceUpdate();
  })

But It cause Warning: Maximum update depth exceeded. and rerender componenet many times. And then I try

 useEffect(() => {
    const timeout = setTimeout(() => {
      forceUpdate()
    }, 0)
    return () => {
      clearTimeout(timeout);
    }
  })

It solved for warning Maximum update depth exceeded.

  • 1
    Because you're force updating in a `useEffect` with no dependencies. So you're force updating every render, which by design causes another render, and therefore an infinite loop. I'm not sure what the goal is here. There are very few good use-cases for needing for force update a component. – Brian Thompson Jul 27 '21 at 14:17
  • I'm curious why the `setTimeout` version *doesn't* cause an infinite loop. Perhaps that's what OP was asking? Maybe it actually causes an infinite loop, but React doesn't detect it so it doesn't generate the warning. – edemaine Jul 27 '21 at 14:38
  • Yes I wonder about setTimeout version doesn’t cause an infinite loop. And I see with setTimeout render less than without setTimeout – Phat Thach Jul 27 '21 at 15:27

0 Answers0