Blog>
Snippets

Using Context API to Manage State in Nested Sub Components

Demonstrates how to use React's Context API to pass state and functions down to deeply nested sub components, avoiding prop drilling and facilitating state management.
import React, { createContext, useState, useContext } from 'react';

// 1. Create Context
const MyContext = createContext();

// 2. Context Provider Component
export const MyProvider = ({ children }) => {
  const [value, setValue] = useState('Initial State');

  const changeValue = newValue => setValue(newValue);

  return (
    <MyContext.Provider value={{ value, changeValue }}>
      {children}
    </MyContext.Provider>
  );
};
This code snippet creates the Context and a Provider component. The Provider component wraps around children components, making the state 'value' and the function 'changeValue' available to any nested components using the Context.
import React from 'react';
import { MyProvider } from './MyProvider';
import { SubComponent } from './SubComponent';

const App = () => (
  <MyProvider>
    <div>
      <h1>Main Component</h1>
      <SubComponent />
    </div>
  </MyProvider>
);
This snippet sets up the basic structure of the application, wrapping the main and nested components within the MyProvider to grant them access to the context data.
import React from 'react';
import { useContext } from 'react';
import { MyContext } from './MyProvider';

export const SubComponent = () => {
  const { value, changeValue } = useContext(MyContext);

  return (
    <div>
      <p>{value}</p>
      <button onClick={() => changeValue('Updated State')}>Change Value</button>
    </div>
  );
};
This code demonstrates a sub component utilizing useContext to access and display the 'value' from the context, and update it using the 'changeValue' function provided through the context.