What Is React Context

What Is React Context?

In simple language, React Context allow you to share data (like theme, language or user info) between components without passing the props.

Suppose you have a : parent component → child → grandchild → great-grandchild.

You can pass values using Props without Context Provider. But, with props first your value goes into parent component → child → grandchild → great-grandchild.

So, If you want to directly send value from parent component to great-grandchild component, so you can send it with React Context Provider.

✅ For Example:

  • Theme switching (dark/light mode)
  • User login info
  • Language preference

✅ For Example : Theme Switching In Your App (Dark/Light Mode).

⚙️Theme Switching Component Tree Using Props:

App

├── Layout (gets `theme`, `setTheme` from App)
│ │
│ ├── Header (gets `theme` from Layout)
│ └── Content (gets `theme`, `setTheme` from Layout)
│ │
│ └── ThemeToggleButton (gets `theme`, `setTheme` from Content)

In this example:

  • You can see, If toggle button will press so first its passing to Content Component, then Header Component, then Layout Component and then passing into App.
  • Using only props, your value goes like this. But if you are using Context Provider so your value pass like below:

⚙️ Context Provider Component Hierarchy:

<App>
├── Header
├── Main
│ ├── Dashboard
│ │ ├── Sidebar
│ │ └── Widget (The Toggle Button Here)
└── Footer

If the Toggle button inside the Widget Component and when user switch the theme, so it will directly pass value to the App component and changed the theme.

Why Use React Context?

  1. Global State Is Required: When you need to manage or add some data in everywhere of your Application like Theme, Login Info, App Settings, You can use Context for this.
  2. Reducing Prop Drilling: Avoid to sending data form one parent to multiple child component, it is called prop drilling.
  3. Consistent State Across Components: If many components use the same data and you update it in one place, so Context change all data automatically.

How To Create Context in React?

Three main steps are required for set up and use context :

  • Create Context : First create new context using React.createContext() to manage shared data across components.
  • Provide Context : Whatever value you want to share, you can pass it using Context.Provider, and wrap the components that need access to that shared value.
  • Consume Context : Use useContext() hook or Context.Consumer to access or update the shared value Inside any child component.

Here, understand these three steps in Theme Context example to change theme(Dark/Light) in any Application.

1. Create Context

Create a context to start by React.createContext(). When you call this function, it give you return a Context object that can use it for both Provide Context and Consume Context.

import React, { createContext } from 'react';

const ThemeContext = createContext();
export default ThemeContext;

Here, we have created a ThemeContext to manage theme-related information in application.

2. Provide Context

Once you have created a context using React.createContext(), Wrap your app in themecontext.provider to share theme data accross your app.

import React, { useState } from 'react';
import ThemeContext from './ThemeContext';

function App() {
const [theme, setTheme] = useState('light');

return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<MyComponent />
</ThemeContext.Provider>
);
}

export default App;

In this example:

  • The Provider component from ThemeContext is wrapping MyComponent.
  • The value prop define the data and functions accessible by any components within ThemeContext.Provider.

3. Consume Context

To access the context data in child components, use the useContext hook.

import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';

function MyComponent() {
const { theme, setTheme } = useContext(ThemeContext);

return (
<div>
<p>Current Theme: {theme}</p>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
}

export default MyComponent;

In this component:

  • We are using useContext(ThemeContext) to access theme and setTheme.
  • This allows MyComponent to display and toggle the theme without receiving props from its parent.

Creating a Language Selector with Context

In this example we create context to manage the application’s language setting. This context can be accessed from any component to display text in the selected language.

Language Context:

Create LanguageContext:

import { createContext, useState } from 'react';

const LanguageContext = createContext();

export function LanguageProvider({ children }) {
const [language, setLanguage] = useState('en');

return (
<LanguageContext.Provider value={{ language, setLanguage }}>
{children}
</LanguageContext.Provider>
);
}

export default LanguageContext;

Here, we create a LanguageContext to store the current language (language) and (setLanguage) function to update the language.

Wrap This App with LanguageProvider:

import React from 'react';
import { LanguageProvider } from './LanguageContext';
import MainComponent from './MainComponent';

function App() {
return (
<LanguageProvider>
<MainComponent />
</LanguageProvider>
);
}

export default App;

This is a wrapper component that use a useState to manage the language value. it wraps the whole app using <LanguageProvider>, so it can access and update all the child component language state.

Use Language Context in Components:

import React, { useContext } from 'react';
import LanguageContext from './LanguageContext';

function LanguageSelector() {
const { language, setLanguage } = useContext(LanguageContext);

return (
<div>
<p>Selected Language: {language}</p>
<button onClick={() => setLanguage('en')}>English</button>
<button onClick={() => setLanguage('es')}>Spanish</button>
</div>
);
}

export default LanguageSelector;

LanguageSelector component access the shared language and setLanguage using the useContext() hook. it allows users to switch the language by buttons.

Using Context with Class Components

If your component is function based so you are use a useContext(). But if your component are class based so you can’t use react hooks, You can use contextType to access context in class component.

Example:

import React, { Component } from 'react';
import ModeContext from './ModeContext'; // Context renamed

class DisplayMode extends Component {
static contextType = ModeContext; // Context accessing in class component

render() {
const { mode, updateMode } = this.context; // Renamed state and setter

return (
<div>
<p>Current Display Mode: {mode}</p>
<button onClick={() => updateMode(mode === 'light' ? 'dark' : 'light')}>
Switch Mode
</button>
</div>
);
}
}

export default DisplayMode;

Here, we use static contextType = ModeContext to access theme in class-based component.

Different Between Context Vs Redux

ContextRedux
React context is best when you share simple global data.React Redux is best when you share more complex state logic and large applications.
For example: Theme(Dark/Light), Login Info and App Language(Hindi, English, etc.)For example: Large Scale Data, Read/Write Complex Data, deep updates, API calls, etc.

Leave a Comment