How to Update Context API in React

This article explains how to dynamically update the React Context API state from child components. You will learn how to pair React’s useState hook with createContext to pass both the current state and its setter function through a Context Provider, allowing any nested component to trigger state updates.

To update the Context API in React, you need to pass an update function (usually the setter function from a useState hook) along with the state value inside the Context Provider’s value prop. Nested components can then consume this context using the useContext hook and call the update function to modify the global state.

Here is a step-by-step implementation:

1. Create the Context

First, initialize the context using createContext. You can set the default value to null or define a placeholder structure.

import { createContext, useState } from 'react';

// Create the Context
export const ThemeContext = createContext(null);

2. Create the Provider Component

Next, create a provider component that manages the active state using the useState hook. Pass both the state variable and the updater function inside an object to the Provider’s value prop.

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

  // Toggle function to update the state
  const toggleTheme = () => {
    setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
  };

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

3. Consume and Update Context in Child Components

Wrap your application (or the relevant component tree) with the ThemeProvider. Then, use the useContext hook in any child component to access and trigger the update function.

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

function ThemeButton() {
  // Destructure the state and updater function from context
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <button onClick={toggleTheme}>
      Active Theme: {theme} (Click to Change)
    </button>
  );
}

By structuring your context this way, any component nested within the provider can trigger re-renders and update the shared state seamlessly.