Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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>
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)
},[])
about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!