3

I'm using a React Native functional component as follows:

export const Component1 = () => {
  const [var1, setVar1] = useState(false);
  setVar1(false);
  return (
    <View...>
  )
}

This goes into an infinite loop, but when I remove the setVar1(false), it doesn't. I assumed the component wouldn't re-render if I kept re-setting var1 to the same false value. How do I prevent this re-render?

gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • 1
    Don't set state directly in the component's body – Konrad Oct 11 '22 at 20:16
  • Where should I set it? – gkeenley Oct 11 '22 at 20:19
  • 1
    When some event occurs for example or inside `useEffect` hook. – Konrad Oct 11 '22 at 20:20
  • It would work if you would change the state after timeout https://codesandbox.io/s/thirsty-surf-owqokm?file=/src/App.js You are getting an infinite loop, because react didn't finish the original render and you are already setting the state which causes the rerender. – Konrad Oct 11 '22 at 20:22
  • If that is true, it would account for the first rerender. But what about the second? – windowsill Oct 11 '22 at 20:27
  • @Konrad Linkowski, you said that the state causes the re-render, but why is it re-rendering if you set the same value? It isn't suppose to re-render. https://stackoverflow.com/questions/59489959/set-state-with-same-value-using-hooks-will-cause-a-rerender . I've just tried something that update the state inside ```useEffect``` with that state as dependency, But I because I updated it to the same state - it didn't cause any infinte loop. So why when you update directly in the component body that what's happens? – Tehila Oct 11 '22 at 20:38
  • [too many rerenders example](https://codesandbox.io/s/jolly-dream-bqs7rh?file=/src/App.js) - I guess that `useState` postpone some work for later in the first render and it doesn't see that the same value has been provided. Just a guess, I'm not an expert – Konrad Oct 11 '22 at 20:47
  • I created a [question](https://stackoverflow.com/questions/74034012/why-doesnt-setstate-usestate-correctly-recognize-same-value-in-the-initial-re) if anyone will be interested – Konrad Oct 11 '22 at 20:55

1 Answers1

0

do not update the state directly it will cause Too many re-renders. and React limits the number of renders to prevent an infinite loop.

what you did is that the setVar1 function gets invoked when the component renders, then updates the state, which causes a re-render and does that infinitely. to prevent this behaviour it should be updated using a condition or an event handler or in useEffect

monim
  • 3,641
  • 2
  • 10
  • 25