Context and Component Composition
Share data without prop drilling using context, and design flexible components with children, slots and compound patterns.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Hooks, Refs and State Patterns
Passing props through five layers of components that do not use them (prop drilling) is a sign you need either better composition or context.
Try composition first
Often you can avoid drilling by passing components as children. Instead of <Layout user={user}> passing user down to a deep Avatar, render <Layout sidebar={<Avatar user={user} />}>. The parent that has the data renders the component that needs it.
Context
createContext plus a Provider makes a value available to every component beneath it, read with useContext (or use in React 19). Good uses: theme, current user, locale, feature flags, and state shared by a compound component.
A typical pattern is a custom provider and hook:
const AuthContext = createContext<Auth | null>(null);
export function useAuth() { const v = useContext(AuthContext); if (!v) throw new Error("useAuth outside AuthProvider"); return v; }
Performance notes
Every consumer re-renders when the context value changes. Keep providers close to where they are needed, split unrelated values into separate contexts, and memoise object values. For frequently changing global state, a store library (Zustand) is usually better.
Composition patterns
- Compound components:
<Tabs>,<Tabs.List>,<Tabs.Panel>sharing state through context. - Render props and slots: pass functions or elements for customisable parts.
- Controlled vs uncontrolled components: let callers own state (
valueplusonChange) or keep it internal with a default.
Good enough to move on
You can build a theme or auth provider with a safe custom hook and a small compound component, and you can explain when context is the wrong tool.
Key concepts
- Prop drilling and when it hurts
- Composition with children and slots
- createContext, Provider and useContext
- Custom provider hooks
- Context re-render behaviour
- Compound components
- Controlled vs uncontrolled components
Mini project
Build an accessible Tabs compound component (Tabs, Tabs.List, Tabs.Trigger, Tabs.Panel) that works both controlled and uncontrolled, plus a ThemeProvider with a useTheme hook.
Check yourself
Why does putting a rapidly changing value (like mouse position) in a top-level context hurt performance?
Free resources
- Passing Data Deeply with Context (react.dev)
- Scaling Up with Reducer and Context (react.dev)