What is useContext and how does it prevent prop drilling?

useContext provides a way to pass data through the component tree without having to pass props down manually at every level (a problem known as "prop drilling").

How it works:

  1. Create Context: Use React.createContext(defaultValue) to create a context object.
  2. Provide Context: Wrap your component tree in a <MyContext.Provider value={data}> to broadcast the data to all descendants.
  3. Consume Context: Any descendant component can call useContext(MyContext) to instantly access the provided value.

Common Use Cases:

  • Global Theme: Toggling between light and dark mode across the entire app.
  • Authentication: Keeping track of the currently logged-in user and their permissions.
  • Localization: Providing translation dictionaries and current language preferences.

Note: Overusing context for rapidly changing state can cause performance issues, as every consumer re-renders when the context value changes.

Code example

tsx
1import React, { createContext, useContext, useState } from 'react';
2
3// 1. Create the Context
4const ThemeContext = createContext({
5 theme: 'light',
6 toggleTheme: () => {},
7});
8
9// 2. Create a Provider Component
10export function ThemeProvider({ children }) {
11 const [theme, setTheme] = useState('light');
12
13 const toggleTheme = () => {
14 setTheme(prev => prev === 'light' ? 'dark' : 'light');
15 };
16
17 return (
18 <ThemeContext.Provider value={{ theme, toggleTheme }}>
19 {children}
20 </ThemeContext.Provider>
21 );
22}
23
24// 3. Consume the Context deeply in the tree
25function ThemeToggleButton() {
26 const { theme, toggleTheme } = useContext(ThemeContext);
27
28 return (
29 <button
30 onClick={toggleTheme}
31 className={
32 theme === 'light'
33 ? 'bg-gray-800 text-white px-4 py-2 rounded'
34 : 'bg-white text-gray-800 px-4 py-2 rounded border'
35 }
36 >
37 Switch to {theme === 'light' ? 'Dark' : 'Light'} Mode
38 </button>
39 );
40}
41
42// Usage in App
43export default function App() {
44 return (
45 <ThemeProvider>
46 <div className="p-8">
47 <h1 className="text-3xl mb-4">Context Example</h1>
48 <ThemeToggleButton />
49 </div>
50 </ThemeProvider>
51 );
52}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.

Open in study app