Sub topic 4
Hooks share logic, not state
This chapter assumes you can write function components, use useState and useEffect, and have read the earlier chapters on the Rules of Hooks and on extracting logic into a hook. Here you will see where a custom hook's state lives, why two calls never interfere, and what to do when you do want shared state.
The core idea
A custom hook is an ordinary function that calls other hooks. It has no state of its own. When a component calls it, every useState and useRef inside the hook is registered on that component, not on the hook function.
Here is the useToggle hook again:
import { useState, useCallback } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}Using it twice in one component gives two independent toggles:
import { useToggle } from './useToggle';
function Panels() {
const [openA, toggleA] = useToggle();
const [openB, toggleB] = useToggle();
return (
<>
<button onClick={toggleA}>{openA ? 'Hide A' : 'Show A'}</button>
<button onClick={toggleB}>{openB ? 'Hide B' : 'Show B'}</button>
</>
);
}Clicking the first button does not affect the second. The two calls do not know about each other.
Where the state actually lives
React keeps a list of hook slots for each mounted component instance. On every render, React walks through your hook calls in order and matches each call to the slot at the same position. This is why the Rules of Hooks require a stable call order.
When Panels renders, the slots look like this:
useTogglecall A:useStateslot 0,useCallbackslot 1.useTogglecall B:useStateslot 2,useCallbackslot 3.
The hook function itself is not in the list. Only the primitive hooks it calls are.
The practical consequences:
- Calling a hook is cheap and safe. You are not creating a shared resource.
- You can call the same hook as many times as you need in one component.
- Replacing inline
useStatecode with a custom hook never changes behavior. The state stays attached to the same component.
What is shared and what is not
| Thing | Shared between callers? | Why |
|---|---|---|
| The hook's code (logic) | Yes | It is one function that every caller runs. |
| State from `useState` and `useReducer` | No | Each call creates a slot on the calling component. |
| Refs from `useRef` | No | Each call creates its own ref object. |
| Effects and their cleanup | No | Each call registers its own effect, which runs and cleans up separately. |
| Module-level variables | Yes | They exist once per JavaScript module, outside React. |
| Context values read with `useContext` | Yes | The value is owned by a provider above the components. |
The last two rows are the only ways a hook can share data, and both are explicit.
Same hook, different components
Isolation holds across components too. Two unrelated components can call useToggle, and each gets its own state. The same is true when you render one component twice:
import { useToggle } from './useToggle';
function Spoiler({ text }) {
const [shown, toggle] = useToggle();
return (
<p>
<button onClick={toggle}>{shown ? 'Hide' : 'Reveal'}</button>
{shown && <span> {text}</span>}
</p>
);
}
export function Page() {
return (
<>
<Spoiler text="The butler did it." />
<Spoiler text="It was a dream." />
</>
);
}Revealing the first spoiler leaves the second hidden. Each Spoiler instance has its own hook slots.
A common mistake: module-level state
Developers sometimes expect a hook to behave like a singleton, so they put the state in a module variable:
import { useState } from 'react';
let count = 0; // one copy for the whole app
export function useBrokenCounter() {
const [, forceRender] = useState(0);
const increment = () => {
count += 1;
forceRender((n) => n + 1);
};
return [count, increment];
}This looks shared, but it fails in several ways:
- Only the component that called
incrementre-renders. Other components using the hook keep showing the old number until something else re-renders them. - With server rendering, the variable lives for the lifetime of the server process, so one user's count can leak into another user's page.
- Tests that run in the same module registry see leftover values from earlier tests.
- React cannot track the variable, so features like concurrent rendering cannot keep it consistent between renders.
When you do want shared state
Sometimes several components must see the same value. A hook cannot do this by itself, but a hook can be the friendly front for a mechanism that does. Pick the mechanism by how far apart the components are.
| Situation | Approach | Where the state lives |
|---|---|---|
| Two siblings or a parent and child | Lift state up and pass it as props | The nearest common parent |
| Many components in one subtree | Context with a provider | The provider component |
| Data outside React, or app-wide stores | `useSyncExternalStore` | The external store |
Lifting state up needs no new tools. The parent calls the hook once and hands the result down:
import { useToggle } from './useToggle';
function Details({ open }) {
return open ? <p>Details are visible.</p> : null;
}
function ToggleButton({ open, onToggle }) {
return <button onClick={onToggle}>{open ? 'Hide' : 'Show'} details</button>;
}
export function Card() {
const [open, toggle] = useToggle();
return (
<>
<ToggleButton open={open} onToggle={toggle} />
<Details open={open} />
</>
);
}There is still only one useToggle call, so there is one piece of state, and both children read it.
With context, the state lives in a provider and the hook only reads it:
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const value = useContext(ThemeContext);
if (value === null) {
throw new Error('useTheme must be used inside a ThemeProvider');
}
return value;
}Every component that calls useTheme sees the same theme, because the useState call is in ThemeProvider, not in useTheme. The hook shares access to state that lives elsewhere. The throw gives a clear error when someone forgets the provider.
For data that lives outside React, such as a browser API or a store library, useSyncExternalStore is the tool. A later chapter covers it.
State belongs to the component instance
Because the slots belong to a component instance at a position in the tree, hook state follows the lifecycle of that instance.
- Unmount loses state. If a component stops rendering, its slots are discarded. Rendering it again starts from the initial values.
- A changed
keyresets state. React treats a new key as a new instance.<Panels key={userId} />gives each user fresh toggles. - Moving a component to another place in the tree resets it too, unless React can match it to the same position and type.
- Initial values are read once. The argument to
useToggle(initial)only seeds the first render. If a parent later passes a differentinitial, the state does not change.
The last point catches many people. This component never updates on after mount, even when defaultOpen changes:
import { useToggle } from './useToggle';
export function Drawer({ defaultOpen }) {
const [on, toggle] = useToggle(defaultOpen);
return <button onClick={toggle}>{on ? 'Close' : 'Open'}</button>;
}If you want a new defaultOpen to restart the component, give it a key such as <Drawer key={String(defaultOpen)} defaultOpen={defaultOpen} />. If the value should always follow the parent, the parent should own the state and pass it down as a controlled prop. Name hook parameters initial... or default... so callers know they are only starting values.
Strict Mode and isolation
In development, React's Strict Mode renders components twice and re-runs effects once on mount to expose impure code. Hook state is still isolated per instance, so a correct hook behaves the same. A hook that increments a module-level counter on render, for example to generate ids, will skip numbers or produce mismatches. Use useId or a ref for per-instance values.
Checklist
When a hook seems to share too much or too little, check these in order:
- Is the data in a module variable? Then it is shared, but React does not track it.
- Are the components calling the hook separately? Then each has its own state, as designed.
- Does the state need to survive unmounting? Then it must live higher up or outside React.
- Is a changed parameter being ignored? It is probably an initial value, which is read once.
Exercise
Two sibling components, CartIcon and CartSummary, each call a hook useCart() that is built on useState([]). Adding an item in CartSummary does not update the badge count in CartIcon. Why does this happen, and name two ways to fix it.
Show answer
Each call to useCart() creates its own useState slot on its own component instance, so the two components hold separate arrays. A hook shares logic, not state. Fix it by lifting the useCart() call into a common parent and passing the cart and its functions down as props. Or move the state into a context provider and make useCart read it with useContext. An external store read with useSyncExternalStore also works.
Exercise
A component renders <Drawer defaultOpen={false} />, and later the parent changes the prop to true. Drawer calls useToggle(defaultOpen). Does the drawer open? What is one way to make it follow the new value?
Show answer
No. The argument to useState inside useToggle is only used on the first render, so later values are ignored. You can reset the instance by giving it a changing key, such as key={String(defaultOpen)}. A better fit when the value should always follow the parent is to have the parent own the state and pass open and onToggle as controlled props.