Architecting Production React Custom Hooks: Composition, Memory Leaks, and Strict TypeScript Safety
React custom hooks are one of the most useful tools for organizing application logic. They allow developers to extract stateful behavior from components, share logic across screens, and create reusable abstractions around browser APIs, network requests, subscriptions, and complex UI interactions.
However, creating a custom hook that works in a small component is very different from designing one that remains reliable in a production application. A hook may behave correctly during initial rendering but fail when dependencies change, a component unmounts, a request completes late, or multiple components use the same abstraction simultaneously.
These problems become more important in applications with complex data flows, authentication, real-time updates, large component trees, and strict TypeScript configurations.
- Designing custom hooks with clear responsibilities and predictable APIs.
- Composing smaller hooks into reusable application-level abstractions.
- Preventing memory leaks and cleaning up external resources.
- Handling asynchronous operations, stale responses, and race conditions.
- Applying strict TypeScript patterns to hook inputs, outputs, and callbacks.
- Testing, profiling, and reviewing custom hooks before production deployment.
- Understanding Custom Hook Architecture
- Production Design Principles
- Custom Hook Composition
- Strict TypeScript Safety
- Memory Leaks and Effect Cleanup
- Async Operations and Race Conditions
- Building Browser API Hooks
- Performance and Re-render Optimization
- Testing Custom Hooks
- Production-Style Example
- Common Architecture Mistakes
- Production Readiness Checklist
- Frequently Asked Questions
1. Understanding Custom Hook Architecture
A custom hook is a JavaScript or TypeScript function that uses React hooks to encapsulate reusable stateful behavior. Its name must begin with use, such as useAuth, useDebounce, or useWindowSize.
Unlike an ordinary utility function, a custom hook can use React state, effects, context, refs, and other hooks. This makes it suitable for extracting behavior that depends on React's rendering lifecycle.
1.1 Why custom hooks matter
Consider a component that manages a search input, debounces user input, sends an API request, tracks loading state, and displays errors. Keeping all this logic inside the component can make it difficult to understand and maintain.
function ProductSearch() {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// Debounce logic
// API request logic
// Error handling
// Request cancellation
return (
<div>
{/* Search UI */}
</div>
);
}
As the component grows, UI rendering and business behavior become tightly coupled. Extracting the behavior into custom hooks provides a cleaner boundary.
function ProductSearch() {
const [query, setQuery] = useState("");
const debouncedQuery = useDebounce(query, 400);
const {
data,
loading,
error
} = useProducts(debouncedQuery);
return (
<SearchResults
query={query}
onQueryChange={setQuery}
products={data}
loading={loading}
error={error}
/>
);
}
The component now focuses on presentation and interaction. The hooks own the reusable behavior.
1.2 Custom hooks share logic, not automatically state
This distinction is important when designing shared application behavior. Calling the same custom hook from two components does not automatically create shared state between them.
function useCounter() {
const [count, setCount] = useState(0);
return {
count,
increment: () => setCount(value => value + 1)
};
}
function FirstCounter() {
const counter = useCounter();
return <button onClick={counter.increment}>
First: {counter.count}
</button>;
}
function SecondCounter() {
const counter = useCounter();
return <button onClick={counter.increment}>
Second: {counter.count}
</button>;
}
Each component has its own independent counter state. The hook shares the implementation, not the state instance.
2. Production Design Principles for Custom Hooks
A production custom hook should have a clear contract. Other developers should be able to understand what it accepts, what it returns, what resources it manages, and how it behaves when its inputs change.
2.1 Give each hook one primary responsibility
A hook should solve a recognizable problem. For example, useDebounce should manage delayed value updates. It should not also perform API calls, manage authentication, and update unrelated application state.
Prefer focused hooks such as:
useDebounce– delays value updates.useProducts– loads product data.useOnlineStatus– tracks browser connectivity.useLocalStorage– synchronizes a value with local storage.useAuth– exposes authentication-related application behavior.useMediaQuery– observes a media query.
Small hooks are easier to test and compose. They also reduce the number of unrelated dependencies a component must understand.
2.2 Design a predictable return contract
Hook return values are an API. Avoid returning inconsistent shapes depending on whether data is available.
For example, this design is difficult for consumers to use:
function useUser() {
if (!userId) {
return null;
}
return {
user,
loading
};
}
The component must now handle multiple return shapes. A more predictable contract is:
type UserResult = {
user: User | null;
loading: boolean;
error: Error | null;
};
function useUser(userId: string | null): UserResult {
// Implementation
}
Now consumers can consistently read the same fields.
2.3 Separate application logic from infrastructure
Production hooks often interact with infrastructure such as APIs, browser storage, timers, event listeners, and WebSocket connections. Keep these boundaries explicit.
For example, a hook should not need to know how an entire HTTP client is configured. It can call a typed API service instead.
// services/userService.ts
export async function getUser(
userId: string,
signal?: AbortSignal
): Promise<User> {
const response = await fetch(
`/api/users/${userId}`,
{ signal }
);
if (!response.ok) {
throw new Error("Unable to load user");
}
return response.json() as Promise<User>;
}
The hook can now manage the React lifecycle while the service owns the HTTP operation.
3. Custom Hook Composition: Building Larger Features from Smaller Hooks
Hook composition is the practice of building a higher-level custom hook by calling other custom hooks. It is one of the strongest architectural techniques for managing complex React behavior.
↓
useProducts
↓
useProductSearch
↓
ProductSearch Component
Each layer has a focused responsibility. The final hook provides a convenient interface for the component without duplicating lower-level implementation details.
3.1 Create reusable foundational hooks
Start with a small debounce hook:
import { useEffect, useState } from "react";
export function useDebounce<T>(
value: T,
delay: number
): T {
const [debouncedValue, setDebouncedValue] =
useState<T>(value);
useEffect(() => {
const timeoutId = window.setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
window.clearTimeout(timeoutId);
};
}, [value, delay]);
return debouncedValue;
}
This hook works with strings, numbers, objects, and other value types. The generic parameter preserves the original value type.
It also clears the previous timer before scheduling another one. Without cleanup, multiple timers could remain active while the user continues typing.
3.2 Compose a data hook
Next, create a hook that loads products for a search query. It should handle loading, data, errors, and cancellation.
type Product = {
id: string;
name: string;
price: number;
};
type ProductsResult = {
data: Product[];
loading: boolean;
error: Error | null;
};
export function useProducts(
query: string
): ProductsResult {
const [data, setData] = useState<Product[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
if (!query.trim()) {
setData([]);
setLoading(false);
setError(null);
return;
}
const controller = new AbortController();
async function loadProducts() {
setLoading(true);
setError(null);
try {
const response = await fetch(
`/api/products?q=${encodeURIComponent(query)}`,
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Product request failed");
}
const products =
await response.json() as Product[];
setData(products);
} catch (cause: unknown) {
if (
cause instanceof Error &&
cause.name === "AbortError"
) {
return;
}
setError(
cause instanceof Error
? cause
: new Error("Unknown product error")
);
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
void loadProducts();
return () => {
controller.abort();
};
}, [query]);
return { data, loading, error };
}
The hook now owns the API lifecycle. Its consumer does not need to know about fetch cancellation or request error conversion.
3.3 Create a feature-level hook
Combine the debounce and data hooks into a feature-level abstraction:
export function useProductSearch(initialQuery = "") {
const [query, setQuery] = useState(initialQuery);
const debouncedQuery = useDebounce(query, 400);
const products = useProducts(debouncedQuery);
return {
query,
setQuery,
...products
};
}
The component can use one hook to access the complete search behavior:
function ProductSearch() {
const {
query,
setQuery,
data,
loading,
error
} = useProductSearch();
return (
<section>
<input
value={query}
onChange={event => setQuery(event.target.value)}
placeholder="Search products"
/>
{loading && <p>Loading...</p>}
{error && <p>{error.message}</p>}
{data.map(product => (
<div key={product.id}>
{product.name}
</div>
))}
</section>
);
}
4. Strict TypeScript Safety for Custom Hooks
TypeScript helps define reliable contracts between hooks and components. However, simply adding a few type annotations does not guarantee safety. Production code should also consider nullability, unknown errors, callback signatures, generic values, and external data validation.
4.1 Enable strict compiler settings
A strict TypeScript configuration catches problems that may otherwise remain hidden until runtime.
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitReturns": true,
"useUnknownInCatchVariables": true
}
}
Not every project must enable every option immediately, especially when migrating an older codebase. However, new hook libraries should aim for strict settings from the beginning.
4.2 Use generics for reusable hooks
Generics allow a hook to preserve the type of the value it receives. This is useful for debounce, previous-value tracking, local storage, and reusable state abstractions.
import { useEffect, useState } from "react";
export function usePrevious<T>(
value: T
): T | undefined {
const [previous, setPrevious] =
useState<T | undefined>(undefined);
useEffect(() => {
setPrevious(value);
}, [value]);
return previous;
}
When a component passes a number, the returned previous value is typed as number | undefined. When it passes a string, TypeScript preserves the string type.
Notice that this implementation updates the previous value after the current render. That timing is intentional: the current render receives the value from the previous committed effect.
4.3 Avoid using any for unknown values
Using any disables important TypeScript checks. This is especially risky when handling API responses and caught exceptions.
Prefer unknown when the type is not yet known, then narrow it before using it.
function getErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === "string") {
return error;
}
return "An unexpected error occurred";
}
This function handles common error shapes without assuming every thrown value is an Error instance.
4.4 Model hook state with discriminated unions
Multiple boolean flags can create impossible states. For example, a data hook might accidentally report that it is loading and failed while also claiming to have completed successfully.
A discriminated union can make these states explicit.
type AsyncState<T> =
| {
status: "idle";
}
| {
status: "loading";
}
| {
status: "success";
data: T;
}
| {
status: "error";
error: Error;
};
A hook can then return one state object:
function useUser(userId: string | null) {
const [state, setState] =
useState<AsyncState<User>>({
status: "idle"
});
// Fetch implementation
return state;
}
Consumers can narrow the state safely:
const userState = useUser(userId);
switch (userState.status) {
case "idle":
return <p>Select a user</p>;
case "loading":
return <p>Loading user...</p>;
case "success":
return <UserProfile user={userState.data} />;
case "error":
return <p>{userState.error.message}</p>;
}
TypeScript can now detect missing state branches and prevent access to fields that do not exist in the current state.
4.5 Type callback contracts explicitly
Custom hooks often expose callbacks for actions such as submitting forms, refreshing data, or responding to events.
type UseFormOptions<T> = {
initialValues: T;
onSubmit: (values: T) => Promise<void>;
};
function useForm<T>({
initialValues,
onSubmit
}: UseFormOptions<T>) {
const [values, setValues] = useState(initialValues);
const [submitting, setSubmitting] = useState(false);
async function submit() {
setSubmitting(true);
try {
await onSubmit(values);
} finally {
setSubmitting(false);
}
}
return {
values,
setValues,
submitting,
submit
};
}
The generic type ensures that the form values passed to the submit callback match the initial value structure.
response.json() as Product[] does not validate data at runtime. API responses are external input. Use runtime validation, such as a schema validator, when data correctness is important.
Production-grade React custom hooks provide reusable stateful logic, but their architecture depends on understanding how JSX expressions are resolved into component references and React elements. Before optimizing hook composition and component behavior, explore how capitalization rules, AST compilation, and dynamic component selection influence the rendering architecture.
Related architecture deep dive: React JSX Element Resolution: Capitalization Rules, AST Compilation, and Dynamic Component Architecture
5. Preventing Memory Leaks in React Custom Hooks
Memory leaks and lifecycle bugs are among the most important issues in production custom hooks. They often occur when a hook starts an external operation but does not correctly stop or release it.
Common sources include:
- Uncleared timers and intervals.
- Unremoved event listeners.
- Unclosed WebSocket connections.
- Unsubscribed external store listeners.
- Uncancelled network requests.
- Observers that remain connected after a component unmounts.
5.1 Understand the useEffect cleanup lifecycle
An effect may return a cleanup function. React runs that cleanup before the effect is set up again with changed dependencies and when the component is removed.
useEffect(() => {
const intervalId = window.setInterval(() => {
console.log("Polling...");
}, 5000);
return () => {
window.clearInterval(intervalId);
};
}, []);
Without clearInterval, the interval may continue running after the component no longer needs it.
For effects that depend on changing values, React first cleans up the previous effect and then runs the new setup. This prevents old subscriptions from remaining active when their dependencies change.
5.2 Clean up event listeners
Browser event listeners are another frequent source of lifecycle problems.
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(
() => navigator.onLine
);
useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return isOnline;
}
The same function references are used for registration and removal. This matters because removeEventListener must receive the matching listener and compatible options.
5.3 Manage observers correctly
Hooks that use ResizeObserver, IntersectionObserver, or MutationObserver must disconnect observers when they are no longer needed.
function useElementSize(
element: HTMLElement | null
) {
const [size, setSize] = useState({
width: 0,
height: 0
});
useEffect(() => {
if (!element) return;
const observer = new ResizeObserver(entries => {
const entry = entries[0];
if (!entry) return;
setSize({
width: entry.contentRect.width,
height: entry.contentRect.height
});
});
observer.observe(element);
return () => {
observer.disconnect();
};
}, [element]);
return size;
}
Disconnecting the observer releases its observation relationship and prevents callbacks from continuing after cleanup.
5.4 Understand Strict Mode effect behavior
React Strict Mode performs additional development-only checks. In current React development behavior, an effect may be set up, cleaned up, and set up again to help reveal effects that do not correctly mirror their cleanup.
This can expose bugs that are difficult to notice in a normal production build, such as duplicate subscriptions, missing cleanup, and effects that assume they run only once.
6. Async Operations, Stale Responses, and Race Conditions
Asynchronous hooks require more care than simple state hooks. A common problem occurs when a user changes a search query quickly and multiple requests are active at the same time.
For example:
- The user searches for "React".
- The first API request starts.
- The user changes the query to "TypeScript".
- A second request starts.
- The second request finishes first.
- The older React request finishes afterward.
If the hook blindly updates state whenever a request completes, the older response can overwrite the newer result.
6.1 Use AbortController for cancellable requests
For APIs that support fetch cancellation, AbortController provides a practical solution.
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const response = await fetch(url, {
signal: controller.signal
});
if (!response.ok) {
throw new Error("Request failed");
}
const result = await response.json();
setData(result);
} catch (error: unknown) {
if (
error instanceof Error &&
error.name === "AbortError"
) {
return;
}
setError(getErrorMessage(error));
}
}
void load();
return () => {
controller.abort();
};
}, [url]);
When the URL changes or the component unmounts, the previous request is aborted. This reduces unnecessary work and prevents a cancelled request from updating the hook's state through the normal success path.
6.2 Use request identifiers when cancellation is unavailable
Not every asynchronous operation supports cancellation. A request identifier can help ensure that only the latest operation updates state.
function useLatestRequest<T>(
request: () => Promise<T>
) {
const requestId = useRef(0);
const [state, setState] =
useState<AsyncState<T>>({
status: "idle"
});
async function execute() {
const currentId = ++requestId.current;
setState({ status: "loading" });
try {
const data = await request();
if (currentId !== requestId.current) {
return;
}
setState({
status: "success",
data
});
} catch (cause: unknown) {
if (currentId !== requestId.current) {
return;
}
setState({
status: "error",
error: cause instanceof Error
? cause
: new Error("Request failed")
});
}
}
return {
state,
execute
};
}
This example illustrates the latest-request pattern, but a production implementation should also invalidate pending requests during unmount and define how the request function's changing identity is handled. A stable service function or explicit request parameters are often preferable to passing an inline function that changes on every render.
6.3 Do not use isMounted refs as a universal solution
Developers sometimes create an isMounted ref and check it before every state update. This is not a substitute for cancelling external work or preventing stale responses.
It also adds lifecycle bookkeeping that can be unnecessary when a proper cleanup strategy already exists. Prefer resource-specific cleanup, request cancellation, and explicit request identity management.
7. Building Browser API Hooks Safely
Browser APIs are useful sources of reusable behavior, but they introduce environment-specific concerns. Some APIs are unavailable during server-side rendering, and browser objects may not exist until the component runs on the client.
7.1 Build an SSR-aware window size hook
type WindowSize = {
width: number;
height: number;
};
function getWindowSize(): WindowSize {
if (typeof window === "undefined") {
return {
width: 0,
height: 0
};
}
return {
width: window.innerWidth,
height: window.innerHeight
};
}
export function useWindowSize(): WindowSize {
const [size, setSize] = useState<WindowSize>(
getWindowSize
);
useEffect(() => {
const updateSize = () => {
setSize(getWindowSize());
};
window.addEventListener("resize", updateSize);
updateSize();
return () => {
window.removeEventListener("resize", updateSize);
};
}, []);
return size;
}
The server-side guard prevents direct access to window when rendering in an environment without browser globals. Depending on the application, the initial server and client output should also be designed to avoid hydration mismatches.
7.2 Use useSyncExternalStore for external subscriptions
When a hook reads from a mutable external store, useSyncExternalStore is often a better fit than manually subscribing inside an effect and copying values into state.
It provides React with a subscription function and a snapshot reader. React can then coordinate updates with its rendering model.
const subscribe = (callback: () => void) => {
window.addEventListener("online", callback);
window.addEventListener("offline", callback);
return () => {
window.removeEventListener("online", callback);
window.removeEventListener("offline", callback);
};
};
const getSnapshot = () => navigator.onLine;
function useOnlineStatus() {
return useSyncExternalStore(
subscribe,
getSnapshot,
() => true
);
}
The third argument supplies a server snapshot. Choose that value based on the application's rendering requirements rather than assuming that the server knows the browser's actual network state.
8. Performance and Re-render Optimization
Custom hooks do not automatically improve performance. A hook that updates state frequently can cause its consuming component to render more often. Good hook architecture makes update behavior predictable and avoids unnecessary work.
8.1 Understand where state updates cause rendering
When a state value changes inside a custom hook, the component using that hook is scheduled to render. This is expected React behavior.
For example, a hook that updates the current mouse position on every pointer movement can cause frequent renders:
function useMousePosition() {
const [position, setPosition] = useState({
x: 0,
y: 0
});
useEffect(() => {
const update = (event: MouseEvent) => {
setPosition({
x: event.clientX,
y: event.clientY
});
};
window.addEventListener("mousemove", update);
return () => {
window.removeEventListener("mousemove", update);
};
}, []);
return position;
}
This may be appropriate for a component that must react to every movement. It may be excessive for a component that only needs an approximate position at a lower frequency.
8.2 Use refs for values that do not drive rendering
Not every changing value belongs in state. A ref can hold mutable information that must persist between renders without triggering a render when it changes.
function usePreviousValue<T>(value: T) {
const previousRef = useRef<T | undefined>(
undefined
);
useEffect(() => {
previousRef.current = value;
}, [value]);
return previousRef.current;
}
Refs are useful for timer identifiers, request identifiers, and mutable integration state. If a value must immediately appear in the UI, state is generally the appropriate choice.
8.3 Avoid unnecessary memoization
useMemo, useCallback, and React.memo can help in specific situations, but they also introduce complexity. They should not be added automatically to every custom hook.
Use memoization when there is a measurable reason, such as:
- An expensive calculation that should not repeat for unrelated renders.
- A callback identity that matters to a memoized child or subscription.
- A derived object passed into a component where identity changes cause meaningful extra work.
Profile the application before and after optimization. React Developer Tools Profiler can help identify components that render frequently and determine whether those renders are expensive.
8.4 Be careful with objects returned from hooks
A hook that returns a new object on every render creates a new reference:
function useCounter() {
const [count, setCount] = useState(0);
return {
count,
increment: () => setCount(value => value + 1)
};
}
This is not automatically a problem. However, if consumers depend on the returned object as a stable reference, it may be worth stabilizing the relevant values or changing the API to return only what consumers need.
Do not memoize the entire return object by default. First identify the consumer and the actual performance requirement.
9. Testing React Custom Hooks
Testing custom hooks verifies behavior independently from the components that consume them. A good test suite should cover normal operation, changing inputs, cleanup, errors, and edge cases.
9.1 Test the observable contract
For a debounce hook, useful tests include:
- The initial value is returned immediately.
- The value changes after the specified delay.
- Rapid updates reset the pending timer.
- Unmounting clears the active timer.
Using React Testing Library's hook testing utilities and fake timers, a test can verify the debounce behavior.
import { renderHook, act } from "@testing-library/react";
import { vi, describe, it, expect, afterEach } from "vitest";
describe("useDebounce", () => {
afterEach(() => {
vi.useRealTimers();
});
it("updates after the delay", () => {
vi.useFakeTimers();
const { result, rerender } = renderHook(
({ value }) => useDebounce(value, 300),
{
initialProps: { value: "React" }
}
);
expect(result.current).toBe("React");
rerender({ value: "TypeScript" });
expect(result.current).toBe("React");
act(() => {
vi.advanceTimersByTime(300);
});
expect(result.current).toBe("TypeScript");
});
});
Adapt the timer setup and cleanup to the testing framework version used by the project. The key point is to control time explicitly instead of waiting for real delays.
9.2 Test effect cleanup
For a subscription hook, verify that the corresponding listener is removed when the hook unmounts.
it("removes the online listener on unmount", () => {
const removeSpy = vi.spyOn(
window,
"removeEventListener"
);
const { unmount } = renderHook(() => useOnlineStatus());
unmount();
expect(removeSpy).toHaveBeenCalledWith(
"online",
expect.any(Function)
);
removeSpy.mockRestore();
});
Also test dependency changes. A hook that subscribes to a different resource when an identifier changes should clean up the old subscription before registering the new one.
9.3 Test asynchronous edge cases
For data hooks, include tests for successful responses, HTTP failures, rejected promises, aborted requests, and out-of-order completion. These cases are more likely to expose production defects than a test that only checks the happy path.
10. Production-Style Example: A Reusable API Hook
The following example brings together several of the principles discussed in this guide: a predictable return contract, strict TypeScript types, request cancellation, error normalization, and explicit loading states.
It is intentionally focused on one resource. In a larger application, the HTTP client, runtime response validation, caching, and retry policy may belong in separate service or data-access layers.
import { useEffect, useState } from "react";
type User = {
id: string;
name: string;
email: string;
};
type ApiState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function normalizeError(cause: unknown): Error {
return cause instanceof Error
? cause
: new Error("An unexpected error occurred");
}
export function useUser(userId: string | null) {
const [state, setState] = useState<ApiState<User>>({
status: "idle"
});
useEffect(() => {
if (!userId) {
setState({ status: "idle" });
return;
}
const controller = new AbortController();
async function loadUser() {
setState({ status: "loading" });
try {
const response = await fetch(
`/api/users/${encodeURIComponent(userId)}`,
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error(
`User request failed: ${response.status}`
);
}
const user = await response.json() as User;
if (!controller.signal.aborted) {
setState({
status: "success",
data: user
});
}
} catch (cause: unknown) {
if (controller.signal.aborted) {
return;
}
setState({
status: "error",
error: normalizeError(cause)
});
}
}
void loadUser();
return () => {
controller.abort();
};
}, [userId]);
return state;
}
A component can consume this hook with exhaustive state handling:
function UserProfile({ userId }: { userId: string }) {
const state = useUser(userId);
switch (state.status) {
case "idle":
return <p>No user selected.</p>;
case "loading":
return <p>Loading user profile...</p>;
case "error":
return <p>{state.error.message}</p>;
case "success":
return (
<section>
<h2>{state.data.name}</h2>
<p>{state.data.email}</p>
</section>
);
}
}
User. Also decide whether previous successful data should remain visible while a new request is loading. That is a product and API contract decision, not merely a TypeScript detail.
11. Common Custom Hook Architecture Mistakes
| Anti-pattern | Why it causes problems | Better approach |
|---|---|---|
| One hook handles everything | Unrelated responsibilities become tightly coupled. | Split behavior into focused hooks and compose them. |
| Missing effect cleanup | Timers, listeners, and subscriptions may remain active. | Return a cleanup function for acquired resources. |
| Using any everywhere | Type checking becomes ineffective. | Use generics, unknown, and explicit contracts. |
| Assuming hook calls share state | Each invocation has independent hook state. | Use Context or a shared store when state must be shared. |
| Ignoring request races | Older responses can overwrite newer data. | Use cancellation or request identity checks. |
| Overusing useMemo | Code becomes harder to understand without proven benefit. | Profile first and optimize measurable bottlenecks. |
| Reading browser globals during server rendering | Code can fail in environments without window or document. | Use environment guards and server-compatible snapshots. |
| Returning inconsistent shapes | Consumers need extra branching and defensive checks. | Define a stable return contract. |
12. Production Readiness Checklist
Before introducing a custom hook into a production React application, review the following points.
- The hook has one clear primary responsibility.
- Its name begins with
use. - It follows the Rules of Hooks.
- Inputs and outputs have explicit TypeScript contracts.
- Strict null checks and unknown error handling are considered.
- External data is validated when runtime correctness matters.
- Every timer, listener, observer, and subscription has appropriate cleanup.
- Network requests handle cancellation where supported.
- Asynchronous responses cannot incorrectly overwrite newer state.
- Browser APIs are handled safely in server-rendered environments.
- Shared state is implemented through an explicit sharing mechanism.
- Memoization is based on actual performance requirements.
- Tests cover dependency changes and cleanup behavior.
- Strict Mode does not expose duplicate-resource or cleanup defects.
- Hook documentation explains important lifecycle and return-value behavior.
13. Final Thoughts
Custom hooks are more than a way to move code out of React components. They are reusable architecture boundaries that can organize application behavior, define clear contracts, and isolate complex interactions with external systems.
Reliable production hooks require more than a correct initial render. They must handle changing dependencies, asynchronous operations, cleanup, runtime data, and TypeScript contracts consistently.
The strongest approach is to begin with small, focused hooks and compose them into feature-level abstractions only when there is a clear reason. Keep resource ownership explicit, make cleanup symmetrical with setup, and treat external data as untrusted until it has been validated.
When these principles are applied consistently, custom hooks become easier to test, reuse, debug, and maintain as a React application grows.
14. Frequently Asked Questions
1. What is a custom hook in React?
A custom hook is a JavaScript or TypeScript function that uses React hooks to encapsulate reusable stateful behavior. It allows multiple components to share logic without duplicating its implementation.
2. Do custom hooks share state between components?
No. Each invocation of a custom hook has its own hook state. To share state between components, use Context, an external store, or another shared state management mechanism.
3. How do you prevent memory leaks in custom hooks?
Clean up resources created by effects. Clear timers, remove event listeners, disconnect observers, unsubscribe from external stores, and cancel requests when possible.
4. Why should custom hooks use TypeScript generics?
Generics allow hooks to work with multiple value types while preserving type information. They are useful for reusable abstractions such as debounce, previous-value, and storage hooks.
5. Should every custom hook use useMemo and useCallback?
No. Memoization should address a real performance requirement. Profile the application and use memoization when it prevents meaningful recalculation or unnecessary work.
6. Can custom hooks be used with server-side rendering?
Yes, but hooks that access browser APIs must account for server environments. Avoid directly accessing window or document during server rendering, and consider server snapshots when using external stores.
7. What is the difference between a custom hook and a utility function?
A utility function is an ordinary function that does not use React's hook lifecycle. A custom hook can use state, effects, context, refs, and other hooks, and must follow the Rules of Hooks.
8. How should custom hooks be tested?
Test their observable behavior, including initial values, state transitions, changing dependencies, error handling, asynchronous races, and cleanup. React Testing Library provides utilities for rendering and testing hooks.
15. Official Documentation and Further Reading
For implementation details and behavior that may change between React versions, use the official documentation as the primary reference.
- React: Reusing Logic with Custom Hooks
- React: Rules of Hooks
- React: useEffect Reference
- React: useSyncExternalStore Reference
- React: StrictMode Reference
- TypeScript: Generics
- TypeScript: Strict Compiler Option
- React Testing Library: API
- MDN: AbortController
Technical note: Examples use modern React function components and TypeScript. Adapt browser APIs, testing utilities, and data-fetching patterns to the React version and runtime environment used by your application.

Comments