React Native: infinite re-render when setting variable to same value

421 Views Asked by At

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?

1

There are 1 best solutions below

0
monim On

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