Context API

Context provides a way to pass data through the component tree without having to pass props down manually at every level. This is commonly used to share "global" data like a user's theme or language preference.

The Problem: Prop Drilling

Normally, data is passed top-down via props. However, this can be cumbersome for certain types of props (e.g., locale, UI theme) that are required by many components within an application.

Creating a Context

To start using context, you first need to create it using React.createContext.

JavaScript

const ThemeContext = React.createContext('light');

Context Provider

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.

JavaScript

<ThemeContext.Provider value="dark">
  <Toolbar />
</ThemeContext.Provider>

Consuming with useContext

The useContext hook is the simplest way to consume context in functional components.

JavaScript

import { useContext } from 'react';

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>I am styled by theme!</button>;
}

Note: Don't use Context just to avoid passing props down a few levels. Context is designed to share data that can be considered "global" for a tree of components.