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

260
Visualizações
Why is Context undefined in child component?

I'm trying to learn React & context.

In the following example, I have my console log correctly the user (which is currently set) in app.js, but in the RequireAuth component (and in its child) logs undefined.

I could probably pass user & setUser as props and have them working, but the goal is to understand what's going wrong and learn how to use context correctly.

Thanks for the help!

userContext.js

import React, { createContext, useContext, useState } from "react";

const UserContext = createContext();

export function useAuth() {
    return useContext(UserContext);
}

const UserProvider = ({ children }) => {
    const [state, setState] = useState(undefined);

    return (
        <UserContext.Provider value={[state, setState]}>
            { children }
        </UserContext.Provider>
    );
}

export default UserProvider;

app.js

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

// Components
// [...]

// Auth Components
import RequireAuth from './requireAuth';

// Context
import UserProvider from './userContext';
import { useAuth } from './userContext';

function App() {

  return (
    <Router>
      <UserProvider>
        <Main />
      </UserProvider>
    </Router>
  );
}

function Main() {
  const [ user, setUser ] = useAuth();
  console.log(user) // LOGS USER
  return (
    <div className="App">
      <Navbar />
      <Title />
      <Routes>
        <Route
          path="/home"
          element={ 
            <RequireAuth>
              <Home />
            </RequireAuth> 
          } />
      </Routes>
      <Footer />
    </div>
  )
}

export default App;

requireAuth.js

import React from 'react';
import { useAuth } from './userContext';


const RequireAuth = ({ children }) => {
    const [ user, setUser ] = useAuth();
    console.log(user) // LOGS UNDEFINED
    
    /* Some logic running if user is set or not */

    return children;
}

export default RequireAuth;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Found what was wrong. My problem was that I didn't use correctly router Links and every time context was reset. The shown code, after setting up the proper Links, works fine.

about 4 years ago · Juan Pablo Isaza Relatório
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