in useState hook when the setState is called it will initializes the state with a new value
i have the example of code below :
import React from 'react'
import ReactDOM from 'react-dom/client'
import { useState } from 'react'
function MyComponent(){
const [status,setStatus] = useState(0);
function update_state(){
setStatus(1);
}
update_state();
return(
<div>
<h1 id='hello'>{status}</h1>
</div>
);
}
const body = ReactDOM.createRoot(document.getElementById("body"));
body.render(<MyComponent/>);
from above code,when the update_state() is called then after that it will initializes the status with a new value but i got this error :
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
where is my mistake, cause i thought when i called the update_state the status will be initializes with 1 but instead i got 1 i got and Uncaught Error
2
Answers
When
setStatus
function is called, React re-renders the component and that makes infinite loop.you need to check
status
in the function to prevent falling in loop.The reason for infinite loop of re-rendering is trying to update the state within the functional component itself. If you want to call
update_state()
as the component renders, you can use useEffect hook in React.First you have to import the hook:
Then inside the functional component call
update_state()
usinguseEffect
:For your reference:
React hooks: What/Why `useEffect`?
https://legacy.reactjs.org/docs/hooks-effect.html