Why is Context undefined in child component?

Viewed 341

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;
1 Answers

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.

Related