Managing State with React useContext

francisldn

Francisldn

Posted on April 24, 2022

Managing State with React useContext

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({});
Enter fullscreen mode Exit fullscreen mode

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

Passing props to components

  • Pass loggedIn and setLoggedIn to Login 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> 
   )
}
Enter fullscreen mode Exit fullscreen mode
đź’– đź’Ş đź™… đźš©
francisldn
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