Sub topic 2
Designing What Goes In and What Comes Out
Assume you know function components, JSX, props, useState, useEffect, destructuring, closures, and promises. A custom hook is a function that uses React hooks and starts with use. Its parameters are the inputs, and its return value is the public API.
Designing the Hook API
Accept values that the caller must control. Return the smallest useful result. A tuple works well for a state value and its action. An object works better when a hook returns several named values.
import { useState, useCallback } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}The caller can write const [open, toggle] = useToggle(). Avoid returning internal state setters unless callers truly need them.
Effects and Cleanup Inside a Hook
A hook may hide an effect when the effect belongs to the behavior it provides. Cleanup prevents old timers, listeners, or subscriptions from continuing after inputs change or the component unmounts.
import { useState, useEffect } from 'react';
export function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}Here, cleanup cancels the previous timer before a new timer starts.
Getting Dependency Arrays Right
A dependency array lists reactive values read by an effect. Include every prop, state value, or function from the component or hook scope that the effect uses. Omitting one can create a stale closure, where the effect reads an old value. Adding a value can intentionally restart the effect when that value changes.
Returning Stable Functions
useCallback returns the same function reference until one of its dependencies changes. This matters when callers pass the function to a memoized child or include it in another effect’s dependencies. It does not make the function’s work faster by itself.
Use functional state updates when the callback only needs the previous state. That keeps its dependency list empty, as useToggle demonstrates.
Exercise
Why does useDebouncedValue include both value and delay in its dependency array?
Show answer
The timer reads both values, so it must be replaced when either one changes.