Why does setState in the body of the component cause an infinite loop even if it's setting the same initial value?

Viewed 69

The code below should not trigger a re-render because it's passing the same initial value right? But it instead causes 'Too many re-renders' error.

function Test() {
   const [counter, setCounter] = useState(0)
   setCounter(0)
   return <></>
}

Edit: If you setCounter(0) in a function and attach it to a button click, it won't trigger a re-render since it has the same value so why does it trigger re-render when placed in the body of the component? I am aware of the useEffect with empty dependency array to avoid the infinite loop.

If you do this, you'll see that it doesn't re-render:

function Test() {
   const [counter, setCounter] = useState(0)

   console.log('render');

   const set = () => {
     setCounter(0)
   };

   return <button onClick={set}>Set</button>
}
2 Answers

In React, It does not Matter You are Updating Same Value or Not. If you Update the State It Will rerender the Component..

In your case , You Have SetState in the body of the Component.. So it will rerender and Cause an Infinite Loop..

If you Just want to Update Once, use useEffect instead.

useEffect(() => {
 setCounter(0)
},[])

If you update the state directly inside your render method or a body of a functional component, it will cause an infinite loop.

State updates → triggers re-render → state updates → triggers re-render → …

You can have look at this article

Related