Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

267
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda