Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!