Question: I am using React Context to pass in the state and setState like this 

```
const [authContext, setAuthData] = useState({
    isAuthenticated: false,
    userID:"-1",
    email:"test",
    name:"test"
  });

<AuthContext.Provider value={[authContext,setAuthData]}>
          <Router>
            <NavbarMenu />
              <div className="AllElements">
                  <Switch>
                    <Route exact path="/" component={HomePage} />
                    <Route component={Routes} />
                  </Switch>
              </div>
          </Router>
        </AuthContext.Provider> 

```

and in another component, I retrieve it like this 

```
const [authContext, setAuthData ] = useContext(AuthContext);
const { isAuthenticated } = authContext;

```

I call setAuthData like this whenever I want to update authContext

```
const HomePage = () => {
if(data && data.login && data.login.token){
        console.log("Data token exists");
        setAuthData(() => [{
            isAuthenticated: true,
            userID:data.login.id,
            email:data.login.email,
            name:data.login.name
        }]);
    } 

 return (<div><p>test</p></div>);
};
export default HomePage;

```

However, once it hits setAuthData, everything inside the if {} gets called multiple times. I keep seeing multiple "Data token exists" in the console until it errors out to Maximum update depth exceeded

Answer: 
You get an infinite loop because setAuthData call changes authContext. When authContext changes HomePage would re-render and it trigger setAuthData again.

Make sure you call setAuthData only once for example:

```
const HomePage = () => {
  React.useEffect(() => {
    if (data && data.login && data.login.token) {
      console.log("Data token exists");
      setAuthData(() => [
        {
          isAuthenticated: true,
          userID: data.login.id,
          email: data.login.email,
          name: data.login.name
        }
      ]);
    }
  }, [data]);

 return (<div><p>test</p></div>);
};

```
I guess you should do the state update in `useEffect` hook and pass the second parameter to react only when it updates: 

```
const HomePage = () => {

    useEffect(()=>{
        //if(data && data.login && data.login.token){
            console.log("Data token exists");
            setAuthData(() => [{
                isAuthenticated: true,
                userID:data.login.id,
                email:data.login.email,
                name:data.login.name
            }]);
       // } 
     }, [data]); //<-----second param if it has any changes then run effect
     return (<div><p>test</p></div>);

};

```