Skip to content

Instantly share code, notes, and snippets.

@ejangi
Created June 24, 2021 03:03
Show Gist options
  • Save ejangi/07d153cd2753dd9082f94ee04cabcbf4 to your computer and use it in GitHub Desktop.
Save ejangi/07d153cd2753dd9082f94ee04cabcbf4 to your computer and use it in GitHub Desktop.
Next JS UserContext and UserProvider example of using React useContext
import { createContext, useState } from 'react';
//create a context, with createContext api
export const userContext = createContext();
const UserProvider = (props) => {
// this state will be shared with all components
const [loggedin, setLoggined] = useState(false);
return (
// this is the provider providing state
<userContext.Provider value={[loggedin, setLoggined]}>
{props.children}
</userContext.Provider>
);
};
export default UserProvider;
// ... In _app.js add the context:
// import UserContext from '../contexts/useUserContext';
// ... and wrap the main component: <UserContext><Component {...pageProps} /></UserContext>
// ... Wherever you need to consume it:
// import { userContext } from '../contexts/useUserContext';
// ... and in the default export function:
// const [loggedin, setLoggedin] = useContext(userContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment