React HooksHard
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:
- Create Context: Use
React.createContext(defaultValue)to create a context object. - Provide Context: Wrap your component tree in a
<MyContext.Provider value={data}>to broadcast the data to all descendants. - 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';23// 1. Create the Context4const ThemeContext = createContext({5 theme: 'light',6 toggleTheme: () => {},7});89// 2. Create a Provider Component10export function ThemeProvider({ children }) {11 const [theme, setTheme] = useState('light');1213 const toggleTheme = () => {14 setTheme(prev => prev === 'light' ? 'dark' : 'light');15 };1617 return (18 <ThemeContext.Provider value={{ theme, toggleTheme }}>19 {children}20 </ThemeContext.Provider>21 );22}2324// 3. Consume the Context deeply in the tree25function ThemeToggleButton() {26 const { theme, toggleTheme } = useContext(ThemeContext);2728 return (29 <button30 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'} Mode38 </button>39 );40}4142// Usage in App43export 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.