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 <></>
}
CodePudding user response:
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)
},[])
CodePudding user response:
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
CodePudding user response:
We always talk about rendering
but it's not the only thing that React does. There is another phase, called the commit
phase, where changes are applied to the DOM, after a comparison between the candidate DOM (Virtual Dom) and what the user already seeing (Real Dom).
When you call setCounter(0)
over and over, React re-renders that component over and over, hence the error you are getting, but never commits as each time the resulted DOM is the same as the previous one. This is called Bailing out of a state update
, explained here:
If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)
Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo.
The question you asked is I think because we people tend to talk about the render
and commit
phases as one thing, just rendering.