Create Context
Learn more about React Context.
lib/context.js
import { createContext } from 'react';
export const UserContext = createContext({ user: null, username: null });
Provide Context
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
components/Navbar.js
import { useContext } from 'react';
import { UserContext } from '../lib/context';
// Top navbar
export default function Navbar() {
const { user, username } = useContext(UserContext)
}
pages/enter.js
import { useContext } from 'react';
import { UserContext } from '../lib/context';
export default function Enter(props) {
const { user, username } = useContext(UserContext)
}