DEV Community

Francisldn
Francisldn

Posted on

5 3 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay