Created
June 24, 2021 03:03
-
-
Save ejangi/07d153cd2753dd9082f94ee04cabcbf4 to your computer and use it in GitHub Desktop.
Next JS UserContext and UserProvider example of using React useContext
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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