Auth Context Manage the global auth state with the React Context API

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
Get Unlimited PRO Access

OR


*Enrollment provides full access to this course (and updates) for life.

Create Context

Learn more about React Context.

file_type_js_official lib/context.js
import { createContext } from 'react';

export const UserContext = createContext({ user: null, username: null });

Provide Context

file_type_js_official pages/_app.js
import { UserContext } from '../lib/context';

function MyApp({ Component, pageProps }) {
  
  return (
    <UserContext.Provider value={{ user: {}, username: 'jeff' }}>
      <Navbar />
      <Component {...pageProps} />
      <Toaster />
    </UserContext.Provider>
  );
}

Consume Context

file_type_js_official components/Navbar.js
import { useContext } from 'react';
import { UserContext } from '../lib/context';

// Top navbar
export default function Navbar() {

  const { user, username } = useContext(UserContext)

}
file_type_js_official pages/enter.js
import { useContext } from 'react';
import { UserContext } from '../lib/context';

export default function Enter(props) {
  const { user, username } = useContext(UserContext)

}

Questions?

Ask questions via GitHub below OR chat on Slack #questions