the react is rendering it infinitly, i dont know how to stop
please say a solution to apply on the attached code below
Error shown in console:
""" [1836] auth.js:15 Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn’t have a dependency array, or one of the dependencies changes on every render.
at AuthProvider (http://localhost:3000/static/js/main.chunk.js:1045:3)"""
import React from "react";
import { useState, useEffect, useContext, createContext } from "react";
const AuthContext = createContext();
const AuthProvider = ({ children }) => {
const [auth, setAuth] = useState({
user: null,
token: "",
});
useEffect(() => {
const data = localStorage.getItem("auth");
if (data) {
const parseData = JSON.parse(data);
setAuth({
...auth,
user: parseData.user,
token: parseData.token,
});
}
}, [auth]);
return (
<AuthContext.Provider value={[auth, setAuth]}>
{children}
</AuthContext.Provider>
);
};
// custom hook
const useAuth = () => useContext(AuthContext);
export { useAuth, AuthProvider };
please comment the corrected code
i need to stop the rendering multiple times
2
Answers
The issue you are encountering is likely due to the fact that you’re using auth as a dependency in the useEffect inside the AuthProvider component. This creates a circular dependency, as updating auth triggers the useEffect, which updates auth again, leading to an infinite loop.
In the First way, we directly set the initial state of auth based on the local storage value. We also remove auth from the dependency array of the useEffect to avoid the infinite loop issue.