🌐 Auth Context

Manage the global auth state with the React Context API

Create Context

Learn more about React Context.

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

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

Provide Context

file_type_js 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 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 pages/enter.js
import { useContext } from 'react';
import { UserContext } from '../lib/context';

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

}

Questions? Let's chat

Open Discord