DEV Community

Francisldn
Francisldn

Posted on

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

Top comments (1)

Collapse
 
lalami profile image
Salah Eddine Lalami

@ IDURAR , we use react context api for all UI parts , and we keep our data layer inside redux .

Here Article about : πŸš€ Mastering Advanced Complex React useContext with useReducer ⭐ (Redux like Style) ⭐ : dev.to/idurar/mastering-advanced-c...


Mastering Advanced Complex React useContext with useReducer (Redux like Style)