Hooks 04 · More complex state
Context
The end of prop drilling, the Provider + hook pattern and performance traps.
Loading lesson…
Hooks 04 · More complex state
The end of prop drilling, the Provider + hook pattern and performance traps.
Loading lesson…
From lesson React basics 01 you know that data flows down the component tree only from top to bottom through props. Mostly that's an advantage – you can clearly see where everything came from. But now the app has a signed-in user, and their photo should show in the sidebar, which is inside the page layout, which is inside the app:
interface User { name: string; photo: string } // name and photo addressfunction App() {// the signed-in user; setUser would be called on sign-in or sign-outconst [user, setUser] = useState<User>({ name: 'Anna', photo: '/anna.jpg' })return <Layout user={user} />}function Layout({ user }: { user: User }) { // doesn't need the user, just carries it onreturn <Sidebar user={user} />}function Sidebar({ user }: { user: User }) { // doesn't need it either, carries it on tooreturn <Avatar user={user} />}function Avatar({ user }: { user: User }) { // finally uses itreturn <img src={user.photo} alt={user.name} />}
It works, but look at what it costs:
Layout and Sidebar have a prop they don't use at all – they just pass it on. They must know the User type even though they do nothing with it.This is called prop drilling. Two or three levels are fine. The trouble starts when the same data is carried through many layers to many places – typically the signed-in user, the colour theme or the language.
The head teacher needs to tell the pupils on the third floor that PE is cancelled this afternoon. Without a PA system they tell the deputy, who tells a teacher in the corridor, who tells the form teacher, who finally tells the pupils. The deputy and the teacher in the corridor don't need the message – they just carry it on. That's prop drilling.
The school solves it with a PA system. The head teacher speaks into a microphone in the PA office and everyone in the building with a loudspeaker hears it. Nobody carries anything. That's exactly what Context is:
The PA system announces things that concern the whole school – not who lent whom a rubber. Context suits data that many places need and that changes rarely. The table shows typical candidates; on the right is whether they belong in context:
| Data | How many places need it? How often does it change? | Context? |
|---|---|---|
| the colour theme, the language, the currency format | almost everywhere, rarely | ✅ yes |
| the signed-in user, permissions | many places, rarely | ✅ yes |
| "services": pop-up messages (toasts), windows over the page | anyone can trigger them | ✅ yes |
| the text the user is typing right now | one field, on every letter | ❌ no, state in the component |
| data from the server | many places, but it has its own tools | ❌ no, lesson Advanced React 08 |
| a value that only needs passing 1–2 levels | a few places | ❌ no, ordinary props |
Every context is made of three parts. We'll show them twice: first in general and then filled in on a colour theme.
// Blanks to fill in: ValueType (the type of what is broadcast), initialValue (the starting state)// and the word My in the names – replace it with what the context is about (Theme, Auth…).import { createContext, use, useState, type ReactNode } from 'react'// ─── 1. THE CHANNEL (createContext) ──────────────────────// What will be broadcast. null = what a component out of the PA office's reach hears.const MyContext = createContext<ValueType | null>(null)// ─── 2. THE PA OFFICE (the Provider) ─────────────────────// An ordinary component: it holds state and broadcasts it to everything it wraps.// children = everything you write in the app between <MyProvider> and </MyProvider>.function MyProvider({ children }: { children: ReactNode }) {const [value, setValue] = useState(initialValue)// broadcasts an object: the value and the function that changes itreturn <MyContext value={{ value, setValue }}>{children}</MyContext>}// ─── 3. THE LOUDSPEAKER (a custom hook) ──────────────────// One place components listen from – with a check that the PA office exists.function useMy() {const ctx = use(MyContext)if (!ctx) throw new Error('useMy must be inside <MyProvider>')return ctx}
Three questions come with a context:
A colour theme: what's broadcast is whether it's light or dark, and a function to switch it.
type Theme = 'light' | 'dark'const ThemeContext = createContext<{ theme: Theme; toggle: () => void } | null>(null)
createContext creates a "channel". The type in angle brackets says what will be broadcast (an object with the theme and a function, or null). The value in round brackets (null) is what a component out of reach of any Provider hears – a loudspeaker without a signal.
function ThemeProvider({ children }: { children: ReactNode }) {const [theme, setTheme] = useState<Theme>('light')const toggle = () => setTheme((t) => (t === 'light' ? 'dark' : 'light')) // switch to the oppositereturn <ThemeContext value={{ theme, toggle }}>{children}</ThemeContext>}// Somewhere at the top of the app:<ThemeProvider><Layout /></ThemeProvider>
<ThemeContext value={…}> is how a Provider is written in React 19. In older code you'll see <ThemeContext.Provider value={…}> – it does the same.children (lesson React basics 02) and their descendants.function useTheme() {const ctx = use(ThemeContext) // listen to the nearest ThemeProvider aboveif (!ctx) throw new Error('useTheme must be inside <ThemeProvider>')return ctx}// Anywhere deep in the tree – without a single prop about the theme:function ThemedButton() {const { theme, toggle } = useTheme()return <button className={theme} onClick={toggle}>Toggle</button>}
A custom hook is an ordinary function whose name starts with use and which calls other hooks inside (in detail in lesson Hooks 05). Why a hook and not use(ThemeContext) directly in every component? When someone forgets to wrap the app in the Provider, without the check they'd get null and, a few lines later, a cryptic "cannot read properties of null" error. With the hook they get a clear message about what's wrong. throw new Error(…) throws an error (lesson JavaScript 07).
toggle() calls setTheme in the Provider. The Provider's state changed.{ theme: 'dark', toggle }.Layout between them reads nothing from the context, so it doesn't have to re-render because of it.What you see: A small app: Layout holds a Sidebar and a "Content" panel. The panels and the button read the theme through useTheme(). Neither Layout nor Sidebar gets any prop about the theme.
Try it:
Layout component. It doesn't contain a single word about the theme – yet both its parts agree.The takeaway: One value in the Provider's state, many listeners anywhere below it, and nobody in between has to carry it.
Loading the interactive part…
Context isn't the only cure for prop drilling. Often plain props are enough, just put together differently – that's called composition (putting components inside each other). Before we show it, look once more at the app from the start of the lesson and ask: why does user have to travel through Layout and Sidebar, which don't need it at all?
The data has to get to where <Avatar user={user} /> is written. At the start of the lesson that line sits in Sidebar, deep down – and user is up in App. The way between them leads through every component on the route, which is why Layout and Sidebar have to carry it.
A simple rule: the component that writes an element needs its data. So the chain disappears when you write <Avatar user={user} /> right in App, where user is, and send the finished element down. You already have a tool for sending finished JSX: a slot and children from lesson React basics 02 – a plain prop of type ReactNode that gets a piece of JSX instead of text.
interface User { name: string; photo: string } // as at the start: the name and the photo's addressfunction App() {const [user, setUser] = useState<User>({ name: 'Anna', photo: '/anna.jpg' })// ① you write Avatar HERE, where user is, and hand it to Layout finished, in the sidebar slotreturn <Layout sidebar={<Avatar user={user} />} />}// ② Layout knows nothing about the user – it gets "something to render" (ReactNode) and only decides WHERE it goesfunction Layout({ sidebar }: { sidebar: ReactNode }) {return (<div className="layout"><Sidebar>{sidebar}</Sidebar> {/* passes the finished element on as children */}<main>Page content</main></div>)}// ③ Sidebar knows nothing either – it renders what it got between its tagsfunction Sidebar({ children }: { children: ReactNode }) {return <aside>{children}</aside>}// ④ the only component that really uses user – unchangedfunction Avatar({ user }: { user: User }) {return <img src={user.photo} alt={user.name} />}
What happens when React renders the app:
App creates the element <Avatar user={user} />. For now it's just a description, "Anna's avatar goes here" – a value like any other, which can be sent in a prop.Layout in the sidebar prop. Layout doesn't unwrap it, it just puts it between the <Sidebar> tags.Sidebar gets it as children and puts it into <aside>.App wrote it, not Sidebar.Like the school from the start, only without the PA system: the head teacher writes the message for the class in their own office and seals it in an envelope. The deputy and the teacher in the corridor still carry the envelope, but they don't need to know what's inside. When the message is different tomorrow, their job doesn't change.
The table shows the difference from the start – what changed in the rows, both versions in the columns:
| Prop drilling (start) | Slot (composition) | |
|---|---|---|
Who knows the User type | App, Layout, Sidebar, Avatar | only App and Avatar |
Who writes <Avatar … /> | Sidebar, deep down | App, where the data is |
| You rename the prop or change the User type | you edit all four components | you edit only App and Avatar |
| A button with the user’s name is added to the header | another user prop through Layout down to the header | Layout gets a second slot: header={<UserButton user={user} />} |
(UserButton in the last row is a made-up component – a button with the user's name.)
A slot works as long as the data is needed by a few elements you can write up at the top. When the user is wanted by the avatar, a button in the header, a menu item, the settings page and buttons deep inside lists, you'd have to write all those elements in App and send them down – App would swell up and the slots would stretch just like the props did before. That's the moment for Context.
A simple rule: the data is needed in one or two places → try a slot. It's needed in many places across the tree → Context.
The PA system has one drawback: it announces everything at once, in a single message. When just one thing changes, the whole message plays again and everyone has to listen, even if the change doesn't concern them at all. It's enough for the canteen to bake pizza instead of serving pasta, and even a class that doesn't go to lunch has to sit through the whole announcement – all it wanted to know was whether PE is cancelled.
Context works the same way. When the Provider broadcasts a new value (React recognises it by getting a different object – a reference from lesson JavaScript 09), everyone who reads the context re-renders – including those that use only part of the value. A whole small example: the signed-in user and a counter in one context. Both can change, but each on its own – the name with a "Switch" button, the counter with a "Clicked" button.
// the file src/App.tsx – ❌ one channel for everythingimport { createContext, use, useState, type ReactNode } from 'react'interface AppValue {user: string // the signed-in user's nameswitchUser: () => void // the function "switch the user"count: number // the counterinc: () => void // the function "add 1"}const AppContext = createContext<AppValue | null>(null)function AppProvider({ children }: { children: ReactNode }) {const [user, setUser] = useState('Anna')const [count, setCount] = useState(0)const switchUser = () => setUser((u) => (u === 'Anna' ? 'Peter' : 'Anna'))const inc = () => setCount((c) => c + 1)// Every change of user OR count creates a NEW object → all listeners re-renderreturn <AppContext value={{ user, switchUser, count, inc }}>{children}</AppContext>}// a loudspeaker with a check – the same pattern as useTheme from chapter 1function useApp() {const ctx = use(AppContext)if (!ctx) throw new Error('useApp must be used inside <AppProvider>')return ctx}function UserBadge() {const { user, switchUser } = useApp() // reads only the user…return ( // …but re-renders on every change of count too<p>👤 {user} <button onClick={switchUser}>Switch</button></p>)}function Counter() {const { count, inc } = useApp() // reads only the counterreturn <button onClick={inc}>Clicked {count}×</button>}export function App() {return (<AppProvider><UserBadge /><Counter /></AppProvider>)}
What happens after a click on "Clicked":
inc() changes the state count in the Provider and the Provider re-renders.{ user, switchUser, count, inc } – a different object than last time, so the context has broadcast a new value.Counter (which needs it) and UserBadge, even though the name is still "Anna". React doesn't check which part of the object a component reads – it only knows the component listens to a channel where something new arrived.The same holds the other way round: after a click on "Switch", Counter re-renders for nothing.
The fix: instead of one channel use several channels – a context for each thing that changes separately. The user and the counter change independently, so each gets its own context. What changes in the code compared with the first version:
createContext there are two: UserContext for the user and CountContext for the counter.AppProvider there are two: UserProvider holds the state user, CountProvider the state count. Each broadcasts only to its own channel.useUser, useCount). The hook a component reads with decides which channel it listens to.App the PA offices sit one inside the other, like two boxes. The components sit in the inner box, and so in the outer one too – they're below both PA offices and hear both channels.The same example, fixed:
// the file src/App.tsx – ✅ two channels, two PA officesimport { createContext, use, useState, type ReactNode } from 'react'// ─── CHANNEL 1: the user ─────────────────────────────────interface UserValue {user: stringswitchUser: () => void}const UserContext = createContext<UserValue | null>(null)function UserProvider({ children }: { children: ReactNode }) {const [user, setUser] = useState('Anna')const switchUser = () => setUser((u) => (u === 'Anna' ? 'Peter' : 'Anna'))// a new object is created only when UserProvider re-renders – that is when user changesreturn <UserContext value={{ user, switchUser }}>{children}</UserContext>}function useUser() {const ctx = use(UserContext)if (!ctx) throw new Error('useUser must be used inside <UserProvider>')return ctx}// ─── CHANNEL 2: the counter ──────────────────────────────interface CountValue {count: numberinc: () => void}const CountContext = createContext<CountValue | null>(null)function CountProvider({ children }: { children: ReactNode }) {const [count, setCount] = useState(0)const inc = () => setCount((c) => c + 1)// a new object is created only when CountProvider re-renders – that is when count changesreturn <CountContext value={{ count, inc }}>{children}</CountContext>}function useCount() {const ctx = use(CountContext)if (!ctx) throw new Error('useCount must be used inside <CountProvider>')return ctx}// ─── COMPONENTS: each listens only to its own channel ────function UserBadge() {const { user, switchUser } = useUser() // listens only to channel 1return (<p>👤 {user} <button onClick={switchUser}>Switch</button></p>)}function Counter() {const { count, inc } = useCount() // listens only to channel 2return <button onClick={inc}>Clicked {count}×</button>}export function App() {return (<UserProvider> {/* outer box: channel 1 */}<CountProvider> {/* inner box: channel 2 */}<UserBadge /> {/* both components are below both PA offices */}<Counter /></CountProvider></UserProvider>)}
What happens now after a click on "Clicked":
inc() changes the state count. It belongs to CountProvider, so only that component re-renders.CountProvider creates a new object { count, inc } → channel 2 broadcasts a new value → Counter re-renders.UserProvider sits above it and its state didn't change, so it didn't re-render and didn't create a new object. Channel 1 broadcast nothing new → UserBadge stays as it is.And after a click on "Switch" it's exactly the other way round: only UserBadge re-renders.
You can try the same in the demo – the left half is the first version, the right half the fixed one.
What you see: Two identical pairs of components: the user's name and a counter. On the left both read from one context, on the right from two separate ones, each with its own Provider. Each card flashes yellow when it re-renders. All of them are wrapped in memo (a tool from lesson Advanced React 04 that skips re-rendering when the props haven't changed), so they don't re-render because of their parent.
Try it:
memo didn't help the name card on the left. A change of context goes around it.The takeaway: Every listener re-renders on every change of its channel. What changes independently goes into separate contexts.
Loading the interactive part…
A common and very effective pattern is to combine Context with the reducer from lesson Hooks 03: the reducer in the Provider holds the task list, and components anywhere below it read the tasks or send actions. It's tempting to send everything through one channel – value={{ tasks, dispatch }}. But then every change of the tasks also re-renders the "Add" button, which doesn't read the tasks at all – it listens to the same channel, and that channel broadcast a new object.
The solution is two channels: one broadcasts the tasks, the other the dispatch function. dispatch is always the same function for a given component (lesson Hooks 03, "a stable dispatch"), so the second channel never broadcasts anything new and the buttons don't re-render because of task changes.
Something here may not add up. In the example below, one PA office, TasksProvider, broadcasts both channels – and a bit earlier (the FAQ "Couldn't both contexts be broadcast from one AppProvider component?") we said that one PA office for two channels doesn't help. What's the difference?
First, remember one rule: React re-renders the listeners when a channel broadcasts a different value than last time. It isn't enough that the PA office re-rendered. What matters is whether there's something different in the channel after it re-renders. Now look at what each channel broadcasts:
| Channel | What it broadcasts | Is it a different value after the PA office re-renders? |
|---|---|---|
the only channel in the first version (AppProvider) | an object { user, switchUser, count, inc } written right in value | yes, every time – every re-render creates a new object, even with the same things inside (two objects are never equal, lesson JavaScript 09) |
the tasks in TasksProvider | the tasks array straight from the state | only when the tasks really changed – and that's exactly when TaskList needs to know |
dispatch in TasksProvider | the dispatch function straight from useReducer | never – React gives the component the same function every time |
So what matters is what the PA office puts into a channel, not how many channels it broadcasts. AppProvider put a new object into its channel on every re-render. If AppProvider broadcast two channels (as the FAQ describes), it would be the same: every re-render would create a new object for both. TasksProvider creates no object – it passes on values it got from React. The channel with dispatch is like the school office's phone number pinned on the wall: the timetable changes every week, but the number stays the same, so whoever just wants to call doesn't have to read anything again.
And why aren't there two PA offices like with the user and the counter? Because it can't be done: the tasks and dispatch both come from one line, const [tasks, dispatch] = useReducer(…). dispatch changes exactly this list, so both values have to be created in the same component.
The nesting is the same as before: two boxes, one inside the other, children in the inner one – so every component hears both channels. Only this time one component returns both boxes. The whole file:
// the file src/tasks.tsximport { createContext, use, useReducer, type Dispatch, type ReactNode } from 'react'// The types and the reducer from lesson Hooks 03 – unchangedinterface Task { id: number; text: string; done: boolean }type Action =| { type: 'added'; id: number; text: string }| { type: 'toggled'; id: number }function tasksReducer(tasks: Task[], action: Action): Task[] {switch (action.type) {case 'added':return [...tasks, { id: action.id, text: action.text, done: false }]case 'toggled':return tasks.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t))}}// ─── TWO CHANNELS ────────────────────────────────────────const TasksContext = createContext<Task[] | null>(null) // 1. the tasksconst TasksDispatchContext = createContext<Dispatch<Action> | null>(null) // 2. the dispatch function// Dispatch<Action> = the type of a dispatch function that accepts actions of type Action// ─── THE PA OFFICE: holds the reducer and broadcasts on both channels ──export function TasksProvider({ children }: { children: ReactNode }) {// one call of useReducer gives both values – that's why one PA office broadcasts themconst [tasks, dispatch] = useReducer(tasksReducer, [])return (// outer box = channel 1: the tasks array from the state, new only when the tasks change<TasksContext value={tasks}>{/* inner box = channel 2: dispatch, always the same function → never anything new */}<TasksDispatchContext value={dispatch}>{children} {/* components below both boxes hear both channels */}</TasksDispatchContext></TasksContext>)}// ─── TWO LOUDSPEAKERS: each listens only to its own channelexport function useTasks() {const tasks = use(TasksContext)if (!tasks) throw new Error('useTasks must be used inside <TasksProvider>')return tasks}export function useTasksDispatch() {const dispatch = use(TasksDispatchContext)if (!dispatch) throw new Error('useTasksDispatch must be used inside <TasksProvider>')return dispatch}
And the components that use the Provider – each takes only what it needs:
// the file src/App.tsximport { TasksProvider, useTasks, useTasksDispatch } from './tasks'// The list READS the tasks → listens to channel 1 and re-renders on every change of themfunction TaskList() {const tasks = useTasks()const dispatch = useTasksDispatch()return (<ul>{tasks.map((t) => (<li key={t.id}><input type="checkbox" checked={t.done} onChange={() => dispatch({ type: 'toggled', id: t.id })} />{t.text}</li>))}</ul>)}// The button DOESN'T read the tasks, it just reports an action → listens only to channel 2, which doesn't changefunction AddTaskButton() {const dispatch = useTasksDispatch()return <button onClick={() => dispatch({ type: 'added', id: Date.now(), text: 'A new task' })}>Add</button>}export function App() {return (<TasksProvider> {/* the PA office wraps everyone who needs the tasks */}<AddTaskButton /><TaskList /></TasksProvider>)}
What happens after a click on "Add":
AddTaskButton calls dispatch with the action 'added'.TaskList re-renders and shows the new task.dispatch function as before → AddTaskButton doesn't re-render because of the context.With one button the saving is small. It pays off when many components send actions and the data changes often – say buttons in every row of a long list.
In the previous part everything worked because TasksProvider sent only values React had given it: the array from the state and the dispatch function. Often, though, you need to send something you write yourself – your own function or object. And here's the second trap: whatever you write right in the component's body is created again on every render.
We'll show it on pop-up messages (toasts): small notes like "Saved" that appear after you click a button. It's a simplified version of the service you'll write in the Notification system challenge. First, what each part is for:
toasts) is state in the Provider, and the Provider renders the messages itself. The buttons don't need to see it – so it isn't broadcast.show function ("show a message") adds a new message to the list. This is what the buttons need: they don't want data, they want to do something. So this time the context broadcasts a function, not data – as if the PA office handed out a button "send a message over the PA".api object ({ show }) is the "remote control" the context broadcasts. Why an object and not show directly? Services usually grow: tomorrow you'll add hide (hide a message) and clear (remove them all). You just add them to the object, and components that already write const { show } = useToast() don't have to change. (API, short for application programming interface, generally means "a set of functions you control something with".)value={api}), useToast reads it from the channel and the button takes show out of it. You won't find the word api in the buttons – const { show } = useToast() is destructuring (lesson JavaScript 03), which picks just show out of the object right away.Without any care the whole file looks like this:
// the file src/App.tsx – ❌ the context value is new on every renderimport { createContext, use, useState, type ReactNode } from 'react'interface ToastApi {show: (msg: string) => void // what the context broadcasts: just the function "show a message"}const ToastContext = createContext<ToastApi | null>(null)function ToastProvider({ children }: { children: ReactNode }) {const [toasts, setToasts] = useState<string[]>([]) // the list of messages that are visibleconst show = (msg: string) => setToasts((all) => [...all, msg]) // a new function on EVERY renderconst api = { show } // a new object on EVERY renderreturn (<ToastContext value={api}> {/* A: api goes into the channel */}{children}{/* the Provider renders the messages itself; they are only added at the end and never removed,so the index as the key is fine here (lesson React basics 02) */}{toasts.map((t, i) => <p key={i}>{t}</p>)}</ToastContext>)}function useToast() {const ctx = use(ToastContext) // B: reads the api object from the channelif (!ctx) throw new Error('useToast must be used inside <ToastProvider>')return ctx}// The button only triggers a message – it doesn't read the list of messages at allfunction SaveButton() {const { show } = useToast() // C: takes the show function out of api (destructuring)return <button onClick={() => show('Saved')}>Save</button>}function DeleteButton() {const { show } = useToast()return <button onClick={() => show('Deleted')}>Delete</button>}export function App() {return (<ToastProvider><SaveButton /><DeleteButton /></ToastProvider>)}
What happens when you click "Save" and the button calls show('Saved'):
toasts changes and ToastProvider re-renders.const show = … creates a new function and the line const api = { show } a new object.===, and two different objects are never equal (lesson JavaScript 09).useToast() – here SaveButton and DeleteButton – even though they only want the show function, which always does the same thing.It's as if the PA office printed a new leaflet with the same phone number for every announcement. The text is the same, but it's a different sheet of paper – and React checks whether it got the same sheet, not what's written on it. With two buttons it's a small thing. But messages are triggered from almost everywhere in an app – from buttons in every table row, from forms, from menus – and every new message would re-render them all.
The fix: ask React to remember the function and the object and return the same ones on the next render – the same sheet, until what it was made from changes. React has two hooks for that. Let's look at them one at a time.
// ❌ a plain function: new on every renderconst show = (msg: string) => setToasts((all) => [...all, msg])// ✅ the same function wrapped in useCallback(function, dependencies)const show = useCallback((msg: string) => setToasts((all) => [...all, msg]), [])
The function inside is still the same, it's just wrapped. useCallback stores it on the first render and on every later one returns the stored one – instead of the new one you're passing it right now.
The second argument, the array [], holds the dependencies – just like with useEffect in lesson Hooks 01. You list everything from the component that the function inside uses. When any of it changes, React stores a new version of the function so it doesn't work with old values. Here the function uses only setToasts, and a setter from useState never changes – so the array stays empty and the function is always the same.
// ❌ a plain object: new on every renderconst api = { show }// ✅ the object made through useMemo(make, dependencies)const api = useMemo(() => ({ show }), [show])
useMemo doesn't get a finished object but a function that makes it: () => ({ show }). On the first render it calls it and stores the result. On later renders it doesn't call it at all and returns the stored object – it makes a new one only when the dependency show changes. And because show is always the same thanks to useCallback, the object is always the same too.
(The round brackets around { show } are needed: without them JavaScript would take the curly braces as the function's body, not as an object – lesson JavaScript 02.)
| What you want to remember | Hook | What you pass it |
|---|---|---|
a function (like show) | useCallback | the function itself |
| any other value (an object, an array, the result of a calculation) | useMemo | a function that makes the value |
After the change only the import and the ToastProvider component change in the file. ToastApi, ToastContext, useToast, both buttons and App stay the same as above:
// the file src/App.tsx – ✅ the changed partsimport { createContext, use, useCallback, useMemo, useState, type ReactNode } from 'react'// … ToastApi and ToastContext unchanged …function ToastProvider({ children }: { children: ReactNode }) {const [toasts, setToasts] = useState<string[]>([])// ① always the same function: inside there's only setToasts, and that never changes → dependencies []const show = useCallback((msg: string) => {setToasts((all) => [...all, msg])}, [])// ② always the same object, as long as show is the same (and thanks to ① it always is)const api = useMemo(() => ({ show }), [show])return (<ToastContext value={api}> {/* the context value no longer changes */}{children}{toasts.map((t, i) => <p key={i}>{t}</p>)}</ToastContext>)}// … useToast, SaveButton, DeleteButton and App unchanged …
What happens now when you click "Save":
toasts changes and ToastProvider re-renders.useCallback returns the stored show function (the dependencies didn't change, the array is empty).useMemo sees that show is the same as last time and returns the stored api object.This section puts the lesson together into steps to come back to when you write your own context. You'll find the same pattern in the Cheat sheets on the React tab.
When a context broadcasts one value and a few functions that change it (the signed-in user, the theme, the language), useState is enough. The example is signing in – replace the words Auth, user, login and logout with your own:
// the file src/auth.tsximport { createContext, use, useState, type ReactNode } from 'react'// 1. WHAT IS BROADCAST – the value and the functions that change itinterface AuthValue {user: string | null // the signed-in user's name, or null = nobodylogin: (name: string) => void // sign in the user with this namelogout: () => void // sign out}// 2. THE CHANNEL – not exported, components read it only through the hook below// null = what a component outside the Provider hearsconst AuthContext = createContext<AuthValue | null>(null)// 3. THE PROVIDER – holds the state and broadcasts it together with the functionsexport function AuthProvider({ children }: { children: ReactNode }) {const [user, setUser] = useState<string | null>(null) // nobody at the startconst value = {user,login: setUser, // setUser('Jane') does exactly what login should – just pass it onlogout: () => setUser(null), // signing out = setting "nobody"}// The Provider sits at the very top and nothing else re-renders it, so a new value// object is created only when someone signs in or out. Then every listener// re-renders – for a value that changes this rarely, that's fine. If it changed often,// split it into more channels as in section 3.return <AuthContext value={value}>{children}</AuthContext>}// 4. THE HOOK – the only place components read the context from; outside the Provider it throws a clear errorexport function useAuth() {const ctx = use(AuthContext)if (!ctx) throw new Error('useAuth must be inside <AuthProvider>')return ctx}// use:// <AuthProvider><App /></AuthProvider>// a component that shows the name: const { user } = useAuth()// <span>{user ?? 'Signed out'}</span>// a component that only changes it: const { login, logout } = useAuth()// <button onClick={() => login('Jane')}>Sign in</button>
The ?? in the usage example is the operator from lesson JavaScript 06: when the left side is null, the value on the right is used.
When several actions change the state of a whole part of the app (a list, a cart, settings), combine the context with a reducer and send the state and dispatch through two channels – section 3, "Separate state and actions". Replace the words Item, Items and the actions with your own:
// the file src/items.tsximport { createContext, use, useReducer, type Dispatch, type ReactNode } from 'react'// 1. THE SHAPE OF THE STATE AND THE ACTIONSinterface Item { id: number; text: string }type Action =| { type: 'item_added'; item: Item }| { type: 'item_removed'; id: number }// 2. THE REDUCER – the rules in one place (lesson Hooks 03), outside the componentfunction itemsReducer(items: Item[], action: Action): Item[] {switch (action.type) {case 'item_added':return [...items, action.item]case 'item_removed':return items.filter((i) => i.id !== action.id)}}// 3. TWO CHANNELS – not exportedconst ItemsContext = createContext<Item[] | null>(null)const ItemsDispatchContext = createContext<Dispatch<Action> | null>(null)// 4. THE PROVIDER – holds the reducer and broadcasts the state and dispatchexport function ItemsProvider({ children }: { children: ReactNode }) {const [items, dispatch] = useReducer(itemsReducer, [])return (<ItemsContext value={items}><ItemsDispatchContext value={dispatch}>{children}</ItemsDispatchContext></ItemsContext>)}// 5. TWO HOOKS – each reads one channel and throws a clear error outside the Providerexport function useItems() {const items = use(ItemsContext)if (!items) throw new Error('useItems must be used inside <ItemsProvider>')return items}export function useItemsDispatch() {const dispatch = use(ItemsDispatchContext)if (!dispatch) throw new Error('useItemsDispatch must be used inside <ItemsProvider>')return dispatch}// use:// <ItemsProvider><App /></ItemsProvider>// a component that shows the data: const items = useItems()// a component that only changes it: const dispatch = useItemsDispatch()// <button onClick={() => dispatch({ type: 'item_removed', id: item.id })}>✕</button>
dispatch separately.Read a value from the context – without passing props through the component in the middle.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The first challenge practises section 1 – the whole Provider + hook pattern. The second practises section 3: a context as a "service" that broadcasts only a function, so the components that trigger messages don't re-render. For every context, first tell yourself: what am I broadcasting, where does the PA office stand and who's listening.
The complete Provider + hook pattern plus content by role. The Page component in between must know nothing about the user – just like the deputy who no longer has to carry the message. What should happen is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
A context as a "service" – exactly how pop-up messages work in libraries like sonner or react-hot-toast. What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
use(Ctx) listens, the components in between know nothing.createContext(null) + a Provider with state + a hook with a check.memo. Split contexts into several channels and separate the state from dispatch.