Sub topic 12
Alternatives: Composition, Context, and State Libraries
This chapter assumes you can lift state into a parent, pass a value and a callback as props, and derive values during render instead of storing copies. It also assumes you know useState, children, and basic hooks. Lifting state is the default tool. This chapter covers what to reach for when it becomes awkward.
When lifting starts to hurt
Lifting state up has a cost that grows with the distance between the owner and the components that use the state. Suppose App owns user, and only Avatar needs it, five levels down. Every component in between must accept user and forward it, even though it never reads it. This is called prop drilling.
Prop drilling is not automatically a bug. Drilled props are explicit, easy to trace, and easy to type-check. Consider an alternative when you see these symptoms:
- Intermediate components accept props only to pass them along.
- Renaming or retyping one prop means editing many files.
- Unrelated components re-render or change whenever the shared state changes shape.
Three alternatives address this. Each solves a different problem, so the choice depends on which symptom you have.
Composition: avoid the pipe entirely
Often the intermediate components do not need to know about the data at all. If a layout component takes other elements as props, the parent can build those elements itself, with the data already attached. The layout then never sees the data.
import { useState } from 'react';
function UserBadge({ name }) {
return <strong>{name}</strong>;
}
function Page({ header, children }) {
return (
<div>
<header>{header}</header>
<main>{children}</main>
</div>
);
}
export default function App() {
const [name, setName] = useState('Ada');
return (
<Page header={<UserBadge name={name} />}>
<input value={name} onChange={e => setName(e.target.value)} />
</Page>
);
}Page has no name prop. App still owns the state and is still the closest common parent of the badge and the input. The difference is that App renders both elements itself and hands them to Page as slots, either through children or through named props like header.
Composition has these properties:
- It adds no new concepts. It is plain props and JSX.
- It removes one or more drilling layers without any hidden data flow.
- The reader can still find every use of
nameby readingApp. - It moves complexity upward. If
Appassembles many slots, it can become crowded.
Try composition first. Many cases of drilling disappear once the middle layers accept children instead of data.
Context: broadcast to any depth
When many components at different depths need the same value, composition gets clumsy. Context lets a provider make a value available to any descendant, without passing props through the levels in between.
import { createContext, useContext, useMemo, useState } from 'react';
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const value = useMemo(() => ({ theme, setTheme }), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (ctx === null) {
throw new Error('useTheme must be used inside a ThemeProvider');
}
return ctx;
}
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Theme: {theme}
</button>
);
}
function Toolbar() {
return (
<div>
<ThemeToggle />
</div>
);
}
export default function App() {
return (
<ThemeProvider>
<Toolbar />
</ThemeProvider>
);
}Notice that context does not replace state. The state still lives in useState, inside ThemeProvider. Context is only the delivery mechanism. Lifting state decides where the state lives, and context decides how it travels from there.
The pattern has three parts:
createContextmakes the context object. Here the default isnull.- A provider component owns the state and passes a value to
Context.Provider. - A custom hook wraps
useContextand checks that a provider exists. A missing provider then gives a clear error instead of a confusingundefinedproperty access.
Gotchas with context
Every component that calls useContext(ThemeContext) re-renders when the provider's value changes. React compares the value with Object.is. If you write value={{ theme, setTheme }} inline, you create a new object on every provider render. All consumers then re-render each time the provider re-renders, even if theme did not change. The useMemo above prevents that. Setter functions from useState have stable identity, so they do not need to be in the dependency list.
Context has no selectors. A consumer that reads only theme still re-renders when anything else in the same value changes. Two approaches reduce this:
- Split unrelated data into separate contexts, such as
UserContextandThemeContext. - Separate frequently changing values from rarely changing ones, for example a state context and a dispatch context.
Context also hides the data flow. When you read ThemeToggle you can no longer see where theme comes from without finding the provider. Use it for values that are truly broad: theme, locale, the current user, a router. Do not use it for every piece of state that happens to be shared by two distant components.
State libraries: external stores
A state library keeps state outside the React tree and lets components subscribe to the parts they use. Zustand, Redux Toolkit, and Jotai are common examples. They differ in style, but they share the core idea: the store is the single source of truth, and components select slices of it.
Here is a small store using Zustand:
import { create } from 'zustand';
const useCartStore = create(set => ({
items: [],
add: item => set(state => ({ items: [...state.items, item] })),
}));
function CartCount() {
const count = useCartStore(state => state.items.length);
return <span>Cart: {count}</span>;
}
function AddButton() {
const add = useCartStore(state => state.add);
return <button onClick={() => add('book')}>Add book</button>;
}
export default function App() {
return (
<>
<AddButton />
<CartCount />
</>
);
}There is no provider and no props. CartCount selects only the length of items, so it re-renders only when that number changes. AddButton selects only the add function, which never changes, so it never re-renders because of cart updates. This selective subscription is the main technical advantage over context.
Libraries bring their own costs:
- They add a dependency and a second way to hold state, which every teammate must learn.
- State changes can come from anywhere, so tracing a bug takes more effort than following props.
- Unit tests must reset or replace the store between tests.
- Server-rendered apps need care so one request's store is not shared with another.
Server data is a separate category
A lot of what developers call "shared state" is a cache of data from a server: lists, profiles, search results. Libraries such as TanStack Query manage fetching, caching, refetching, and loading states for this data. If you lift fetched data into a parent and write the loading logic by hand, check whether a server-state library would remove that code. Keep client state, such as which tab is open or what is typed in a form, in useState or a small store.
How the options relate
The diagram shows where each option sits. The data path moves from an explicit chain, through a broadcast, to an external store.
Comparing the options
| Option | Data path | Re-render control | Main cost |
|---|---|---|---|
| Lifted state with props | Explicit, parent to child | Only components that receive changed props | Prop drilling when the tree is deep |
| Composition | Explicit, built by the owner | Same as props | The owner can become crowded |
| Context | Implicit, provider to any consumer | All consumers of the changed context | Hidden data flow, broad re-renders |
| External store | Implicit, store to subscribers | Per-selector subscription | Extra dependency and a second state model |
Failure modes
- Reaching for context too early. Two cousins sharing a value do not need a provider. Lift the state to their parent first. Context is easy to add and awkward to remove once many components call the hook.
- A single giant context. Putting user, theme, cart, and form data into one value means any change re-renders every consumer. Split by how often and why data changes.
- Using a store as a dumping ground. If local UI state, such as whether a dropdown is open, goes into a global store, components lose their independence and become harder to reuse. Keep state as local as it can be.
- Duplicating state across mechanisms. Copying a store value into
useStateto "work with it" recreates the sibling sync problem from earlier chapters. Read from the store, or derive a value during render. - Forgetting the default value. A context created with
createContext(null)returnsnulloutside a provider. Without a guard in the hook, you get an error far from the real cause.
Migrating without a rewrite
These approaches do not conflict, and you can adopt them gradually. A provider can hold the same useState that used to live in App, so moving from lifted state to context changes where the hook is called, not how it works. Components that consume the value only through a custom hook, such as useTheme, can later switch from context to a store by changing the hook's body. Wrapping access in a hook from the start keeps that future change small.
Exercise
A page has a UserMenu nested six levels below App. The App component owns user. Four of the intermediate components only forward user to their child. Name two changes that could remove the forwarding, and say how you would decide between them.
Show answer
Use composition: have App build <UserMenu user={user} /> and pass it to the layout as children or a named slot, so the middle components no longer see user. Or use context: put user in a provider and read it in UserMenu with useContext. Choose composition when the middle components can accept elements, because the data flow stays visible. Choose context when many components at different depths need user, and when the value changes rarely so broad re-renders are not a concern.
Exercise
Your ThemeProvider passes value={{ theme, setTheme }} inline, and a profiler shows every consumer re-rendering whenever the provider's parent re-renders, even though theme is unchanged. What is the cause, and what is the fix?
Show answer
The inline object literal is a new object on each render, so Object.is sees a changed value and React re-renders all consumers. Wrap the value in useMemo(() => ({ theme, setTheme }), [theme]) so its identity changes only when theme changes.
Exercise
In the Zustand example, why does AddButton not re-render when items are added to the cart, while CartCount does?
Show answer
Each component subscribes through a selector. AddButton selects the add function, whose identity never changes. CartCount selects items.length, which changes when an item is added. The store re-renders a component only when its selected value changes.