skip to Main Content

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


    • You have added state dependency in useEffect and setState in useEffect that occurred infinite loop.
    • Either remove [auth] dependency in useEffect or add condition to don’t do again setState after once it is done.
    Login or Signup to reply.
  1. 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.

    const AuthContext = createContext();
    
    const AuthProvider = ({ children }) => {
      const storedAuth = JSON.parse(localStorage.getItem("auth")) || {
        user: null,
        token: "",
      };
    
      // ** First Way
      const [auth, setAuth] = useState({
      user: parseData.user,
      token: parseData.token});
    
     // ** Second way
     // const [auth, setAuth] = useState({user: null, token:""})
     // useEffect(()=>{setAuth(storedAuth)},[storedAuth])
      
      return (
        <AuthContext.Provider value={[auth, setAuth]}>
          {children}
        </AuthContext.Provider>
      );
    };
    
    // custom hook
    const useAuth = () => useContext(AuthContext);
    
    export { useAuth, AuthProvider };
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search