How to Implement React Context API

This article provides a straightforward, step-by-step guide on how to implement the Context API in React. You will learn how to bypass prop drilling by creating a global state, setting up a Context Provider to share data, and consuming that data across your components using the useContext hook.

Step 1: Create the Context

To start, you need to initialize the context using the createContext function from React. This creates an object that will hold your global data.

import { createContext } from 'react';

const ThemeContext = createContext(null);
export default ThemeContext;

Step 2: Build the Context Provider

The Provider component wraps the parts of your application that need access to the context. It accepts a value prop, which contains the data or functions you want to share.

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

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
  };

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

Step 3: Wrap Your Application

To make the context available globally, wrap your root component (usually App or index) with the Provider component you created in Step 2.

import React from 'react';
import { ThemeProvider } from './ThemeProvider';
import MainComponent from './MainComponent';

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

export default App;

Step 4: Consume the Context with useContext

Now, any nested component can access the shared state. Use the useContext hook and pass your created context object as an argument to retrieve the values.

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

const MainComponent = () => {
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <div style={{ 
      background: theme === 'light' ? '#fff' : '#333', 
      color: theme === 'light' ? '#000' : '#fff',
      padding: '20px' 
    }}>
      <p>The current theme is {theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
};

export default MainComponent;