ReactJS - createContext()



CreateContext is a React function that allows us to create a context for components. This function provides or receives data without having to manually send props to every level of the component tree. Context is most important when data needs to be shared throughout many components in our application.

Syntax

const MyContext = createContext(defaultVal)

Parameters

defaultVal − The defaultVal is the value we want the context to have when there is no matching context provider in the tree above the component that reads context. If we don't have a logical default value, leave it null.

Return Value

The createContext() function returns a context object. This object has two components: a Provider and a Consumer. The Provider lets components share the data, and the Consumer lets components access that shared data.

In simple terms, createContext is like creating a special room where components can put information they want to share, and other components can pick it up without a lot of hassle. It makes sharing data in a React app more organized and less complicated.

Examples

Example − Switch Between Languages

Context in React allows components to share data without passing it through props. Here's how you can create and use context with a simple example −

Create a context − In the below code we have created a LanguageContext with a default value of 'English'.

import { createContext } from 'react';
const LanguageContext = createContext('English');

Use context in components − In the below code, the LanguageContext can now be accessed by the Greeting component without receiving it as a prop.

import React, { useContext } from 'react';

function Greeting() {
   const language = useContext(LanguageContext);   
   return <p>{`Hello, ${language}!`}</p>;
}

In a higher-level component, include the following context values

In the App component, we have used LanguageContext.Provider to provide the context value, in our case it is the 'language'. This context will be passed to the Greeting component and any other components contained within it. They will automatically update when the language changes.

import React, { useState } from 'react';

function App() {
   const [language, setLanguage] = useState('English');   
   return (
      <LanguageContext.Provider value={language}>
      <Greeting />
      <button onClick={() => setLanguage('Hindi')}>Switch to Hindi</button>
      </LanguageContext.Provider>
   );
}

export default App;

For example, if we click the "Switch to Hindi" option, the Greeting component will change to say "Hello, Hindi!"

Complete code

In this way, Context provides a clean and efficient way to communicate data in our React application without having to manually pass it down through each level of the component tree.

import React, { createContext, useContext, useState } from 'react';

// Create a LanguageContext
const LanguageContext = createContext('English');

// Create a Greeting component
function Greeting() {
   const language = useContext(LanguageContext);   
   return <p>{`Hello, ${language}!`}</p>;
}

// Create the App component
function App() {
   const [language, setLanguage] = useState('English');   
   return (
      <div style={{marginLeft: '500px'}}>
      <LanguageContext.Provider value={language}>
         <Greeting />
         <button onClick={() => setLanguage('Hindi')}>Switch to Hindi</button>
      </LanguageContext.Provider>
      </div>
   );
}

export default App;

Output

hello english

Example − Change Background Color App

This React app shows the use of the createContext, useContext, and useState hooks to create a simple theming functionality in which the background color of a component changes based on the selected color theme. The code for this app is given below −

import React, { createContext, useContext, useState } from 'react';

// Create a ColorContext
const ColorContext = createContext('lightblue');
// Create a ThemedComponent component
function ThemedComponent() {
   const color = useContext(ColorContext);
   return <div style={{ backgroundColor: color, padding: '20px' }}>Themed
   Component</div>;
}

// Create the ColorApp component
function ColorApp() {
   const [color, setColor] = useState('lightblue');
   return (
      <div>
         <ColorContext.Provider value={color}>
            <ThemedComponent />
            <button onClick={() => setColor('lightblue')}>Switch to blue</button>
            <button onClick={() => setColor('lightpink')}>Switch to Pink</button>
         </ColorContext.Provider>
      </div>
   );
}
export default ColorApp;

Output

themed component

Example − Theme Switcher App

This React app shows the use of the createContext, useContext, and useState hooks to implement theme-switching functionality. The background color of a component changes between light and dark themes based on a user’s interaction with a button. The code is given below for this app −

import React, { createContext, useContext, useState } from 'react';

// Create a ThemeContext
const ThemeContext = createContext('light');

// Create a ThemedContent component
function ThemedContent() {
   const theme = useContext(ThemeContext);
   return <div style={{ background: theme === 'light' ? '#fff' : '#333', padding: '20px' }}>Themed Content</div>;
}

// Create the ThemeSwitcherApp component
function ThemeSwitcherApp() {
   const [theme, setTheme] = useState('light');
   return (
      <div>
         <ThemeContext.Provider value={theme}>
         <ThemedContent />
         <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Toggle Theme</button>
         </ThemeContext.Provider>
      </div>
   );
}

export default ThemeSwitcherApp;

Output

toggle theme

Summary

In this tutorial, we learned about the React function createContext, which makes it simple to create a context for components. The primary goal of createContext is to allow components to share or receive data without manually passing props through every level of the component tree. This is particularly helpful when data has to be exchanged throughout multiple components of an application.

reactjs_reference_api.htm
Advertisements