Search code examples
javascriptreactjsuse-effectuse-state

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.


Solution

  • 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.