Sub topic 5
Designing what goes in and what comes out
This chapter assumes you know function components, useState, useEffect, and modern JavaScript (destructuring, closures, arrow functions). You have already seen how to extract logic into a custom hook. Now the question is the shape of the hook: what it accepts and what it returns.
A hook's signature is its public API. Callers depend on it, so changing it later breaks every component that uses the hook. A few minutes of design up front saves a lot of rework.
Why the signature matters
A custom hook is a plain function. React does not care about its parameters or its return value. That freedom is the reason to be deliberate. Good signatures share three traits:
- The common case needs few or no arguments.
- The return value is easy to read at the call site.
- Wrong usage is hard, because the shape of the API steers the caller.
Choosing parameters
Use positional arguments for one or two required values
When a hook needs one or two obvious inputs, positional arguments read well:
const debounced = useDebouncedValue(query, 300);The call site is short, and the meaning of each argument is clear from context. Once you have three or more arguments, or several optional ones, a call like useThing(a, true, null, 500) becomes unreadable.
Use an options object for optional settings
Put the required value first and group optional settings in an object. Defaults go in the destructuring:
import { useState, useEffect } from 'react';
export function usePolling(url, { intervalMs = 5000, enabled = true } = {}) {
const [data, setData] = useState(null);
useEffect(() => {
if (!enabled) return undefined;
let ignore = false;
async function load() {
const res = await fetch(url);
const json = await res.json();
if (!ignore) setData(json);
}
load();
const id = setInterval(load, intervalMs);
return () => {
ignore = true;
clearInterval(id);
};
}, [url, intervalMs, enabled]);
return data;
}The trailing = {} matters. Without it, usePolling(url) throws, because destructuring undefined is an error. Named options also let you add a new setting later without breaking existing callers.
Pass primitives where you can
Every render creates new objects and arrays. If a hook lists an object parameter in an effect's dependency array, the effect re-runs on every render, even when the contents are identical. Prefer primitives (strings, numbers, booleans) as inputs, or document that callers must keep object arguments stable.
Notice that usePolling above destructures the options object into primitives (intervalMs, enabled) and lists those in the dependencies, not the options object itself. This is why the call usePolling(url, { intervalMs: 1000 }) does not cause a re-run on every render.
Accept an initial value, and treat it as initial
Following useState, a parameter named initial or initialValue is read only on the first render. Changing it later has no effect. Name it accordingly so callers do not expect it to be "controlled". If you do want the hook to follow a changing input, name the parameter for what it is (value, url) and handle changes in an effect.
Choosing return values
Return a tuple when there are one or two values and callers will rename them
Tuples (arrays) work well when the caller will usually name the results themselves. This is why useState returns an array:
const [openA, toggleA] = useToggle();
const [openB, toggleB] = useToggle();With an object return, the caller would have to rename both fields every time they use the hook twice: const { on: openA, toggle: toggleA } = useToggle(). The array form avoids that.
Return an object when there are three or more values, or the order is unclear
Objects let callers pick only what they need and do not depend on order:
const { status, data, error } = useFetchJson(url);Adding a field to an object return is non-breaking. Adding a position to a tuple is non-breaking only at the end, and reordering breaks everyone.
| Situation | Prefer | Reason |
|---|---|---|
| One value | The value itself | No wrapper needed |
| Two values, usually renamed | Tuple | Short call sites, like `useState` |
| Three or more values | Object | Order does not matter, easy to extend |
| Caller uses a subset | Object | Destructure only what is needed |
| Many consumers add fields over time | Object | Non-breaking growth |
Return a state shape that cannot contradict itself
Separate booleans invite impossible combinations. This version allows loading: true and error set at once:
// Easy to get wrong
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [data, setData] = useState(null);A single status field makes the valid states explicit: 'loading', 'success', or 'error'. The useFetchJson hook from this tutorial returns { status, data, error } for this reason. Callers branch on status and cannot end up in a state the hook never intended.
Return only what callers need
Every returned value is a promise to keep supporting it. Do not expose raw setters such as setOn when a narrow operation like toggle expresses the intent. A narrow API also lets you change the internals later.
Stability of returned values
Callers may put your returned functions in their own dependency arrays or pass them to memoized children. If the hook returns a new function on every render, those usages re-run or re-render needlessly. Wrap returned functions in useCallback when they are meant to be used that way, as useToggle does. A later chapter covers this in detail. For design purposes, decide whether stability is part of your contract and document it.
Putting it together
Here is a hook that applies these ideas. It tracks a list of items with add and remove operations and returns an object because there are several values:
import { useState, useCallback } from 'react';
export function useList(initial = [], { maxItems = Infinity } = {}) {
const [items, setItems] = useState(initial);
const add = useCallback(
(item) => {
setItems((current) =>
current.length >= maxItems ? current : [...current, item]
);
},
[maxItems]
);
const remove = useCallback((index) => {
setItems((current) => current.filter((_, i) => i !== index));
}, []);
const clear = useCallback(() => setItems([]), []);
return { items, add, remove, clear };
}Check the design against the points above:
- The first parameter is the initial value, with a default, and the second is an options object with a default for the whole object.
maxItemsis a primitive, so theuseCallbackdependency is stable.- The updater form
setItems((current) => ...)meansadd,remove, andcleardo not depend onitems, so they keep a stable identity. - The return is an object because there are four values.
- The raw setter
setItemsis not exposed. Callers can only do the operations the hook supports.
A caller reads naturally:
function Todo() {
const { items, add, remove } = useList([], { maxItems: 10 });
return (
<ul>
{items.map((item, i) => (
<li key={item}>
{item} <button onClick={() => remove(i)}>x</button>
</li>
))}
<button onClick={() => add(`Task ${items.length + 1}`)}>Add</button>
</ul>
);
}Common design mistakes
- Too many positional arguments. Switch to an options object after the second or third.
- Forgetting the default for the options object.
function useX(a, { b } )fails when the caller omits the second argument. - Object or array parameters in dependencies. They cause effects to re-run each render.
- Inconsistent return shapes. Returning a tuple from some branches and an object from others forces callers to handle both. Always return the same shape.
- Leaking internals. Exposing raw setters or refs lets callers break invariants that the hook maintains.
- Boolean flag soup. Use one
statusvalue when states are mutually exclusive.
Diagram: choosing a return shape
Exercises
Exercise
A hook is declared as function useWindowSize(options) { const { debounceMs = 100 } = options; ... }. A component calls useWindowSize() with no arguments and the app crashes. What is the cause, and how do you fix it?
Show answer
Destructuring options fails because it is undefined when the caller passes nothing. Give the parameter a default object: function useWindowSize({ debounceMs = 100 } = {}). Now calling useWindowSize() works and debounceMs defaults to 100.
Exercise
A hook useUser(id) returns { loading, error, data } as three separate state values. Describe one impossible state this allows and propose a better return shape.
Show answer
With separate flags, the hook can return loading: true while error is still set from a previous request, or loading: false with both data and error null. A better shape is a single status field with values such as 'loading', 'success', and 'error', returned with data and error, for example { status, data, error }. Callers then branch on one value.
Exercise
You write useInterval(callback, { delay: 1000 }) and list options in the effect's dependency array. The interval restarts on every render. Why, and what is the fix?
Show answer
The literal { delay: 1000 } is a new object each render, so options has a new identity every time and the effect re-runs. Destructure the options and depend on the primitive value: function useInterval(callback, { delay = 1000 } = {}) with [delay] in the dependency array.