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

258
Views
React.js (useState ,useEffect) infinite loop error when setState("updated value") is called
import React, {useState,useEffect} from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';

function AppTwo(props){
    const [state, setState] = React.useState("initial value");
    useEffect(() => {
      console.log(`useEffect: ${state}`);
    },[state]);
    
    setState("updated value");
    
    console.log(state);
    return `<h1>${state}</h1>`;
}

ReactDOM.render(
    <>
        <AppTwo />
    </>,
  document.getElementById('root')
);

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Don't call setState inside of the component body. It will update every time the component re-renders. That's why you are getting an infinite loop of state updates.

about 4 years ago · Juan Pablo Isaza Report

0

WORKS!

import React, {useState,useEffect} from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';

function AppTwo(props){
    const [state, setState] = React.useState("initial value");
    useEffect(() => {
      console.log(`useEffect: ${state}`);
    //   document.getElementById('btn').innerHTML = `<h1>State: ${state}</h1>`;
    },[state]);
    
    console.log(state);
    return (
    <>
        <h1>State: {state}</h1>
        <button id="btn" onClick={() => {setState('updated value')}}>
        click
        </button>
    </>
    )
}

ReactDOM.render(
    <>
        <AppTwo />
    </>,
  document.getElementById('root')
);
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!