title: ReactJS Auth context lost when reloading page
body: <p>I'm new to ReactJS and am building a basic application. Here I'm using protected router and implementing an authorization mechanism with useContext and local storage. The aim is to redirect users that are not logged in to the Login Page if they attempt to access Dashboard.</p>
  <p>After I do log in, the access token is saved to local storage and account info is saved in auth context. Then I go to Dashboard and I reload the page. I implemented a useEffect hook to check for token in local storage and I thought that when I reload at the Dashboard page, the auth provider would check for the token and return a result that I'm authenticated. However it doesn't work as expected so I am redirected to Login page (Although the useEffect callback was triggered)</p>
  <p><a href="https://i.stack.imgur.com/gUr9b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gUr9b.png" alt="enter image description here" /></a></p>
  <p>Below is my code:</p>
  <p><strong>src\components\App\index.js</strong></p>
  <pre><code>import { Routes, Route } from 'react-router-dom';
  
  import Login from '../Login';
  import Signup from '../Signup';
  import GlobalStyles from '../GlobalStyles';
  import ThemeProvider from 'react-bootstrap/ThemeProvider';
  import RequireAuth from '../RequireAuth';
  import Layout from '../Layout';
  import Dashboard from '../Dashboard';
  import Account from '../Account';
  
  function App() {
      return (
          &lt;GlobalStyles&gt;
              &lt;ThemeProvider&gt;
                  &lt;Routes&gt;
                      &lt;Route path=&quot;/&quot; element={&lt;Login /&gt;} /&gt;
                      &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;
                      &lt;Route path=&quot;/signup&quot; element={&lt;Signup /&gt;} /&gt;
                      &lt;Route element={&lt;RequireAuth /&gt;}&gt;
                          &lt;Route path=&quot;/&quot; element={&lt;Layout /&gt;}&gt;
                              &lt;Route path=&quot;/dashboard&quot; element={&lt;Dashboard /&gt;} /&gt;
                              &lt;Route path=&quot;/account&quot; element={&lt;Account /&gt;} /&gt;
                          &lt;/Route&gt;
                      &lt;/Route&gt;
                  &lt;/Routes&gt;
              &lt;/ThemeProvider&gt;
          &lt;/GlobalStyles&gt;
      );
  }
  
  export default App;
  </code></pre>
  <p><strong>src\components\RequireAuth\index.js</strong></p>
  <pre><code>import { useLocation, Navigate, Outlet } from 'react-router-dom';
  import useAuth from '../../hooks/useAuth';
  
  function RequireAuth() {
      const { auth } = useAuth();
      const location = useLocation();
  
      return auth?.user ? (
          &lt;Outlet /&gt;
      ) : (
          &lt;Navigate to={{ pathname: '/', state: { from: location } }} replace /&gt;
      );
  }
  
  export default RequireAuth;
  </code></pre>
  <p><strong>src\hooks\useAuth.js</strong></p>
  <pre><code>import { useContext } from 'react';
  import { AuthContext } from '../context/AuthProvider';
  
  function useAuth() {
      return useContext(AuthContext);
  }
  
  export default useAuth;
  </code></pre>
  <p><strong>src\context\AuthProvider.js</strong></p>
  <pre><code>import { useEffect } from 'react';
  import { createContext, useState } from 'react';
  
  import api from '../helper/api';
  
  const AuthContext = createContext({});
  
  function AuthProvider({ children }) {
      const [auth, setAuth] = useState({});
  
      useEffect(() =&gt; {
          const apiHelper = new api();
          apiHelper.getAccountInfo().then((response) =&gt; {
              setAuth(response.data);
          });
      }, []);
  
      console.log(auth.user);
  
      return (
          &lt;AuthContext.Provider value={{ auth, setAuth }}&gt;
              {children}
          &lt;/AuthContext.Provider&gt;
      );
  }
  
  export { AuthContext, AuthProvider };
  </code></pre>
  <p><strong>src\components\Login\index.js</strong></p>
  <pre><code>import { useState, useRef, useEffect } from 'react';
  import clsx from 'clsx';
  
  import { Form, FormGroup, Button } from 'react-bootstrap';
  import Alert from 'react-bootstrap/Alert';
  import FloatingLabel from 'react-bootstrap/FloatingLabel';
  import { useNavigate } from 'react-router';
  
  import styles from './style.module.scss';
  import logo from '../../assets/images/logo.png';
  import LoadingSpinner from '../LoadingSpinner';
  
  import api from '../../helper/api';
  import useAuth from '../../hooks/useAuth';
  
  const Login = () =&gt; {
      const usernameRef = useRef();
      const errorRef = useRef();
  
      const [state, setState] = useState({
          username: '',
          password: ''
      });
      const { username, password } = state;
      const [error, setError] = useState();
      const [loading, setLoading] = useState(false);
  
      useEffect(() =&gt; {
          usernameRef.current.focus();
      }, []);
  
      const { setAuth } = useAuth();
  
      const navigate = useNavigate();
  
      const submitForm = (event) =&gt; {
          event.preventDefault();
          setLoading(true);
          const apiHelper = new api();
          apiHelper
              .login({
                  username,
                  password
              })
              .then((response) =&gt; {
                  setLoading(false);
                  setError();
                  setAuth({ user: response.data.user });
                  localStorage.setItem('token', response.data.token);
                  navigate('/dashboard');
              })
              .catch((error) =&gt; {
                  setLoading(false);
                  setError(error.response.data.message);
                  usernameRef.current.focus();
              });
      };
  
      return (
          /** Some hmtml */
      );
  };
  
  export default Login;
  </code></pre>
  <p>A video on how the error occurs: <a href="https://streamable.com/b1cp1t" rel="nofollow noreferrer">https://streamable.com/b1cp1t</a></p>
  <p>Can anyone tell me where I'm wrong and how to fix it? Many thanks in advance!</p>