Is it correct that if a state is set to the same value as its initial value (like here we do setCount(1)), React will not trigger a re-render?
Regardless of the incorrect usage of the setCount in the render logic in the provided code snippet, I’m curious why it leads to infinite re-renders. This inquiry is solely for learning purposes.
function App(props) {
const [count,setCount]=useState(1)
setCount(1)
return (
<div className='App'>
<h1>{count}</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
3
Answers
It will re render infinitely ! See this stackblitz for confirmation : https://stackblitz.com/edit/stackblitz-starters-psegx9?file=src%2FApp.tsx
The setX function always trigger a re-render (see https://react.dev/reference/react/useState#setstate). Thus you will have infinite rerenders since you call setCount on render.
To avoid this and depending on your use case, you could use something like useMemo.
It works like this when you run the code:
note: even though the value didn’t change, you assigned a new value (with a different memory address)
…
That’s why you put it inside
useEffect
, which like usestate isn’t triggered each time a rerender occursA react component has a certain lifecycle.
The lifecycle has certain phases, one of them being
render
:Now what is happening in the above code is that render phase is not being completed. It is being interrupted by
setState
which triggers another call, and queues a state update.React has a bailing behaviour, which helps it bails out of state updates based on certain conditions. This does not happen everytime though.
Quote from docs:
Now the problem here is that a tree is not generated, and React has nothing to compare the previous and the current DOM structure.
Look at the below code:
{child:true}
is never logged. Which means that even before the render phase is completed (and the tree build) the next render is triggered.Link to above sandbox
When we put the above code inside a
useEffect
, React is able to diff between the two trees created.Now, even if we are essentially doing the same thing as earlier but because we are letting the tree being created, React is able to bail out of state update.
Link to above sandbox