0
0
Reactframework~5 mins

Creating context in React

Choose your learning style9 modes available
Introduction

Context lets you share data easily across many parts of your app without passing props step-by-step.

You want to share user login info across many components.
You need a theme (like dark or light mode) available everywhere.
You want to manage language settings globally.
You want to avoid passing the same data through many layers of components.
Syntax
React
import { createContext } from 'react';

const MyContext = createContext(defaultValue);

export default MyContext;

createContext makes a new context object.

You can give a defaultValue used when no provider is found.

Examples
This creates a context for theme with default 'light'.
React
import { createContext } from 'react';

const ThemeContext = createContext('light');
This creates a context for user info starting as null.
React
import { createContext } from 'react';

const UserContext = createContext(null);
Sample Program

This example shows how to create a context for language settings, provide it to components, and update it from a child component.

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

// 1. Create context with default value
const LanguageContext = createContext('English');

// 2. Create a provider component
function LanguageProvider({ children }) {
  const [language, setLanguage] = useState('English');

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

// 3. Create a component that uses the context
function LanguageSwitcher() {
  const { language, setLanguage } = useContext(LanguageContext);

  return (
    <div>
      <p>Current language: {language}</p>
      <button onClick={() => setLanguage('Spanish')}>Switch to Spanish</button>
      <button onClick={() => setLanguage('English')}>Switch to English</button>
    </div>
  );
}

// 4. Use provider at top level
export default function App() {
  return (
    <LanguageProvider>
      <LanguageSwitcher />
    </LanguageProvider>
  );
}
OutputSuccess
Important Notes

Always wrap components that use context inside the provider.

Context is great for global data but avoid overusing it for everything.

Summary

Context shares data without passing props manually.

Create context with createContext().

Use a provider to supply data and useContext() to consume it.