i am currently learning react, but i have this error
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
and this is the code
const [Status, setStatus] = useState(false);
if (sessionStorage.getItem("token")) {
setStatus(true);
}```
CodePudding user response:
You are doing a state change while rendering your component. By doing a state change you are triggering a new rendering, therefor you are creating a rendering loop.
You have to use the useEffect hook in order to set your local state to your token value at first load. Here is the documentation:
https://reactjs.org/docs/hooks-effect.html
In your case you'll have to replace:
if (sessionStorage.getItem("token")) {
setStatus(true);
}
by:
useEffect(() => {
if (sessionStorage.getItem("token")) {
setStatus(true);
}
}, [])
You can leave the dependency array as empty if you want to trigger it only at first rendering of the component, or gives it dependencies that if they changes will trigger the useEffect again.
CodePudding user response:
setStatus
triggers a re-render and since the sessionStorage
hasn't changed the if condition will stay true. Thus you render endless and react aborts with the error message you posted.
You should use a useEffect
that only triggers if the session storage changes. Something like this:
const token = sessionStorage.getItem("token");
useEffect(() => {
setStatus(token !== undefined);
}, [token]);
or leave the dependency array empty to only execute the effect once (when the component is mounted).
useEffect(() => {
if (sessionStorage.getItem("token")) {
setStatus(true);
}
}, []);