React Hooks Series
useContext
Consume shared state anywhere in the component tree, no prop drilling required. useContext lets any child read from a provider no matter how deeply nested it is.
01 — How it works
01
Three steps// 1. Create the context
export const AppContext = createContext(null);
// 2. Wrap children in a Provider with a value
<AppContext.Provider value={{ username, setUsername }}>
<App />
</AppContext.Provider>
// 3. Consume it anywhere in the tree
const { username } = useContext(AppContext);Every component that calls
useContext(AppContext) will re-render when the context value changes. For large apps, consider splitting contexts by concern.02
Typing context in TypeScriptinterface AppContextType {
username: string;
setUsername: (val: string) => void;
}
// null default + type guard in consumers
export const AppContext = createContext<AppContextType | null>(null);
// In consumer:
const ctx = useContext(AppContext);
if (!ctx) return null; // type guard02 — Live demo
↓
ContextTutorial — interactiveType a username in the Login component. The User component reads it from context — no props passed between them.
AppContext.Provider
Login (child)
User (child)
Not logged in
No props passed between Login and User — they both read from context
Next: useMemo — skip expensive recalculations by memoizing derived values.