React
/Advanced
Provider Pattern
Definition
A pattern that uses React Context to 'provide' data to many components deep in the tree, completely bypassing prop drilling.
Explain Like I'm New
It's like installing a Wi-Fi router in your house. The Provider is the router. Once it's turned on, any device in the house (any nested component) can connect to the Wi-Fi using the password (`useContext`), without running a physical wire (Props) through every room.
Real World Example
Wrapping the entire `<App>` in a `<ThemeProvider>` so that any component, no matter how deep, can call `const theme = useTheme()`.
Common Use Cases
- •Theming
- •Authentication
- •Routing state
Interactive Example
import { createContext, useContext, useState } from 'react'; const ThemeContext = createContext(); export function ThemeProvider({ children }) { const [theme, setTheme] = useState('light'); return <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>; }
Interview Questions
basic
- What are the two parts of the Provider pattern?
intermediate
- Why should you be careful about what data you put in a Provider?
advanced
- How do you prevent massive re-renders when a Provider value changes?