Sub topic 12
Alternatives: composition, context, and state libraries
This chapter assumes you can lift state into a common parent and pass values and callbacks as props. It covers what to try when that pattern starts to cost more than it saves.
When lifting gets heavy
Lifting works well when the owner and the components that use the state are a few levels apart. The cost appears when the state passes through components that never use it. A prop that a component only forwards is called prop drilling. Each intermediate component then has to know about the prop, and renaming or adding one means editing every layer.
Drilling is not always a problem. Two or three levels of explicit props are easy to trace. Look for another approach when intermediate components are changing only to pass data along.
Composition: pass elements, not data
Often the intermediate components don't need to receive the data. They only need to render something. If the parent builds the elements that use the state and passes them in as props or children, the layers in between never see the state.
import { useState } from 'react';
function Layout({ sidebar, content }) {
return (
<div style={{ display: 'flex', gap: '2rem' }}>
<aside>{sidebar}</aside>
<main>{content}</main>
</div>
);
}
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
export default function App() {
const [text, setText] = useState('');
return (
<Layout
sidebar={<Field label="Edit" value={text} onChange={setText} />}
content={<p>Preview: {text}</p>}
/>
);
}App owns text and creates both elements. Layout only arranges them, so it has no text or onChange props. State is still lifted, but the path from owner to user is short. Try this first, because it adds no new concepts.
Context: share a value with a whole subtree
Context lets a component provide a value that any descendant can read, at any depth. This fits data that many distant components need, such as the current theme, the signed-in user, or the locale.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext({ theme: 'light', setTheme: () => {} });
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
function ThemeButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Theme: {theme}
</button>
);
}
function Toolbar() {
return <ThemeButton />;
}
export default function App() {
return (
<ThemeProvider>
<Toolbar />
</ThemeProvider>
);
}Toolbar takes no props, yet ThemeButton can read and update the theme. The state still lives in one owner, ThemeProvider, so the single source of truth rule holds.
Context has costs:
- Every component that calls
useContextre-renders when the provided value changes. A new object invalue={{ theme, setTheme }}is created on each render of the provider, so consumers can re-render more often than you expect. - Data flow becomes implicit. A reader can't see from the props where a component gets its data.
- Components that read context are harder to reuse and test outside a provider.
State libraries
Libraries such as Redux Toolkit, Zustand, and Jotai keep state in a store outside the component tree. Components subscribe to the slices they need, so a change re-renders only the subscribers of that slice. Server data from an API is a separate case. Tools such as TanStack Query manage it as a cache, and you usually shouldn't copy it into your own state.
A library earns its place when many unrelated parts of the app share state that changes often, or when you need features like time-travel debugging, middleware, or persistence. For a form or a single screen, it is usually more machinery than you need.
Choosing an approach
Exercise
A Page component renders Header, which renders UserMenu. UserMenu needs the current user's name, and Header does not use it. Name two ways to avoid passing user through Header as a prop.
Show answer
Composition: Page creates <UserMenu user={user} /> and passes it to Header as a prop or as children, so Header only renders it. Context: a UserContext provider wraps the tree, and UserMenu reads the user with useContext. Composition is the simpler choice here, because the user is only needed in one place.