Skip to main content

The Context API

Usually, you pass information from a parent component to a child component via props. However, passing props can become verbose and inconvenient if you have to pass them through many components in the middle, or if many components in your app need the exact same information.

Passing props through components that do not need the data just to reach a distant child is known as prop drilling.

Solving Prop Drilling with Context

Context lets a parent component provide data to the entire tree below it, no matter how deep, without passing it directly through props.

1. Create the Context

Create the context object, usually in a separate file so it can be exported.

import { createContext } from 'react';

export const ThemeContext = createContext('light');

2. Provide the Context

Wrap the parent component tree with a Provider, and supply the value you want to broadcast.

import { ThemeContext } from './ThemeContext.jsx';
import Dashboard from './Dashboard.jsx';

export default function App() {
const currentTheme = 'dark';

return (
<ThemeContext.Provider value={currentTheme}>
<Dashboard />
</ThemeContext.Provider>
);
}

3. Consume the Context

Any component inside the Provider hierarchy can read the value using the useContext hook.

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

export default function Sidebar() {
const theme = useContext(ThemeContext);

return <div className={`sidebar-${theme}`}>...</div>;
}

Context is primarily used for global user authentication, visual themes, or locale language settings. For high-frequency state changes, specialized external stores like Redux Toolkit are highly recommended.