Francisldn
Posted on April 24, 2022
This is a short post to explain how one can use React useContext
hook to create global state variables, thus allowing for props to be passed onto different components easily and avoiding "prop-drilling".
Set up Context file
- Create a context component using
createContext
import {createContext, useState} from 'react'
export const LoginContext = createContext({});
Wrap components with Context.Provider
- Wrap all components within
LoginContext
. All components will have access to the LoginContext props. - Note that the props are passed in using
{{double curly braces}}
.
import {LoginContext} from './Context'
export function App() {
const [loggedIn, setLoggedIn] = useState(false)
return(
<LoginContext.Provider value={{loggedIn, setLoggedIn}}>
<Home />
<Login />
<Profile />
</LoginContext.Provider>
)
}
Passing props to components
- Pass
loggedIn
andsetLoggedIn
toLogin
component - Login component can access the props from LoginContext through
useContext
- Note the use of
{curly braces}
instead of[square brackets]
for props destructuring.
import {LoginContext} from '../Context';
import React, {useContext} from 'react';
export const Login = () => {
const {loggedIn, setLoggedIn} = useContext(LoginContext);
return (
<div>
<button onClick={() => setLoggedIn(!loggedIn)}>Click
here to login
</button>
{loggedIn? <h1>You are logged in</h1>: <h1>You are
not logged in</h1>}
</div>
)
}
đź’– đź’Ş đź™… đźš©
Francisldn
Posted on April 24, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Why useState hook returns array and not object? Let's create a custom hook to see
August 14, 2022