Zulfikar Ditya
Zulfikar Ditya

Reputation: 45

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

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);
    }```

Upvotes: 3

Views: 3097

Answers (2)

Ivo
Ivo

Reputation: 2510

You are doing a state change while rendering your component. By doing a state change you are triggering a new rendering, therefore 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 give it dependencies that if they changes will trigger the useEffect again.

Upvotes: 6

René Link
René Link

Reputation: 51343

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);
    }
}, []);

Upvotes: 3

Related Questions