Custom Hooks in React
Building custom React hooks: extracting reusable stateful logic, naming conventions (use*), returning values/tuples, and real-world examples (useDebounce, useLocalStorage).
Custom Hooks in React
A Custom Hook is a JavaScript function whose name starts with use and that may call other React hooks. Custom hooks let you extract component logic into reusable functions.
1. Custom Hook Rules
- Must start with
use(e.g.useDebounce,useMediaQuery): This allows React linter plugins to enforce hook rules. - Can call other hooks: Inside a custom hook, you can call
useState,useEffect,useRef, etc. - State is isolated: Each call to a custom hook creates an independent state instance.
2. Practical Example: useDebounce
Delay updating search queries to prevent flooding backend APIs with every keystroke:
import { useState, useEffect } from "react";
export function useDebounce<T>(value: T, delayMs: number = 300): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delayMs);
return () => clearTimeout(handler);
}, [value, delayMs]);
return debouncedValue;
}Consuming useDebounce:
export function SearchComponent() {
const [search, setSearch] = useState("");
const debouncedQuery = useDebounce(search, 500);
useEffect(() => {
if (debouncedQuery) {
console.log("Fetching API for:", debouncedQuery);
}
}, [debouncedQuery]);
return <input value={search} onChange={e => setSearch(e.target.value)} />;
}Related Topics
The useCallback Hook in React
Caching callback function definitions with useCallback: preventing unnecessary re-renders of memoized child components and custom hook dependencies.
React Context & Global State
Sharing global state with React Context: createContext, useContext, Provider patterns, avoiding prop drilling, and performance considerations.