React Context & useContext() Hook

Dhruv Parmar
5 min readNov 4, 2023

--

Hello, my dear friends!!, In this blog, we’ll discuss what is React Context, What is its use case? Why was it introduced? etc. And I’m sure, that till the end of this blog, you will get the basic idea of React Context and when to use it.

Table of Contents:

  • What is React Context?
  • What is the useContext() hook?
  • Use Case
  • How do you define Context in your project?

What is React Context?

React Context is a core feature of React, and it was introduced in React version 16.3. It is particularly useful for managing global state, theme settings like (Dark modes 🌙), authentication status, and other data that needs to be accessed by multiple components at different levels of the component hierarchy structure.

In React Application, if we wanna access a state in a child component, then we need to pass that state in a prop. There is nothing wrong with it, right? But what if we need to pass that state to the nested child components in a hierarchy structure? (i.e.: Parent Component => Child Component => Child Component => Child Component). It becomes a tedious task to manage that prop.

Prop-Drilling Example
Prop-Drilling Example

Let's see a simple example of it:

import React, { useState } from 'react'

function YourComponent () {
const [title, setTitle] = useState('Passing Props Demo')

return (
<Card title={title} btn={'Read More'} />
)
}

function Card ({ title, btn }) {
return (
<div className='card'>
<CardTitle name={title} />
<button className='btn btn-sm btn-dark'>{btn}</button>
</div>
)
}

function CardTitle ({ name }) {
return (
<span>{name}</span>
)
}

export default YourComponent;

So, now here the React Context comes into the picture. The main thing to use React Context is to avoid a prop-drilling issue. In short, we can say that, we can avoid passing props from the parent component to its child or nested child component, like hierarchy structure.

There are mainly three steps to be followed to define React Context.

  • Create Context
  • Provide Context and
  • Consume that Context in your react components
Behind the Scene: looks something like this

I hope, till now you will be clear about the React Context concept and why it was introduced 😊. Let’s see the useContext() hook provided by the React Application.

What is the useContext() hook?

The useContext() is a hook provided by React version 16.8. Yes, it was introduced to connect React Context in your project easily. The useContext() hook is a built-in React hook that allows you to access the value of a context object created with React.createContext() without the need for a Consumer component.

The useContext() hook only accepts one argument and that is the current Context object. With the help of useContext() hook, it becomes easy to access the current context value.

Note: The useContext() hook can only be used in functional component. But the React Context API can be used in both Class based components as well as Function based component.

Usage:

The React Context can be used to avoid passing props to your child components, sharing data like user authentication, theme configuration, and preferred language (i.e.: translate your React app into different language features, etc).

How do you define Context in your project?

Before we move further, let’s see what is React Context API. React Context API is not a separate library or package; it’s a built-in feature of React. It refers to the specific set of functions & components you use to work with React Context.

The Context API includes functions like createContext(), which you use to create a new context and the useContext hook for consuming the context in functional components. It also includes the Provider component for wrapping parts of your component tree with context.

Let's see, how to define Context in your React App with a simple example:

//create a Login.js file for your Login Component
import React, { useState, useContext } from 'react'
import { Form } from 'react-bootstrap'
import UserContext from './context/UserContext'

function Login () {
const [userName, setUserName] = useState('')
const [password, setPassword] = useState('')

const { setUser } = useContext(UserContext)

const handleSubmit = (e) => {
e?.preventDefault()
setUser({ userName, password })
}

return (
<Form>
<h2>Login</h2>
<input className='form-control' type='text' value={userName} onChange={(e) => setUserName(e.target.value)} placeholder='Enter the user-name' />
<input className='form-control' type='password' value={password} onChange={(e) => setPassword(e.target.value)} placeholder='Enter the password' />

<button type='submit' className='btn btn-sm btn-dark' onClick={(e) => handleSubmit(e)}>Login</button>
</Form>
)
}

export default Login
//now create a Dashboard.js file to display the name of user in Dashboard
import React, { useContext } from 'react'
import UserContext from './context/UserContext'

export default function Dashboard () {
const {user} = useContext(UserContext)
return (
<div>
<h1>Dashboard</h1><hr />
<p>UserName: {user?.userName}</p>
</div>
)
}
//now create the UserContext.js file to create context
import React from 'react'

const UserContext = React.createContext()

export default UserContext

//now create the UserContextProvider.js file to provide the context
import React, {useState} from 'react'
import UserContext from './UserContext'

const UserContextProvider = ({ children }) => {
const [user, setUser] = useState (null)

return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
)
}

export default UserContextProvider

Now, wrap the UserContextProvider in your App.js file

import React from 'react'
import Login from './components/Login'
import Dashboard from './components/Dashboard'
import UserContextProvider from './context/UserContextProvider'

export default function App () {
return (
<UserContextProvider>
<Login />
<Dashboard />
</UserContextProvider>
)
}

Conclusion:

I hope, now you will be clear about React Context, React Context API, why it was introduced, when to use it and how to define it.

If you like my content then do follow my account and also share this blog to your friends.

--

--

Dhruv Parmar
Dhruv Parmar

No responses yet