Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

96
Visualizações
Context is reset to null when browser URL is manually changed

I have created AuthContext that holds currently logged in user:

// auth-context.ts
export interface IAuthContext {
  auth: IMe | null;
  setAuth: (user: IMe | null) => void;
}

const AuthContext = React.createContext<IAuthContext>({
  auth: null,
  setAuth: (auth: IMe | null) => {}
});

export default AuthContext;

The simplified main rendered App component where I use the context provider looks like this:

const App: FC = () => {

  const [auth, setAuth] = useState<IMe | null>(null); // problematic line

  return (
    <AuthContext.Provider value={{auth, setAuth}}>
      <BrowserRouter>
        <Routes>
          <Route path='/' element={<Main/>}/>
          <Route path="/login" element={<Login/>}/>
          <Route path="/register" element={<Register/>}/>
          <Route path="/about" element={<About/>}/>
        </Routes>
      </BrowserRouter>
    </AuthContext.Provider>
  );
}

Overall, the application works fine.

However, when I navigate the application by manual URL changes in the web browser, followed-up by hitting the Enter (therefore: page refresh), then there is a problem with auth context reset to null...

I think when I change the URL manually then the whole App component is re-rendered and therefore the AuthContext state is reseted to null by the problematic line.

The idea is that the Login component is using the setAuth inside of it after the form-related promise is positively resolved.

Any tip how can I protect myself from that re-render problem, and therefore context resettng to default null value? I think this scenario is kind of basic, but I am beginner in frontend stuff. Thank you!

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda