React Hooks
React Custom Hooks
A custom hook is a function whose name starts with "use" and which calls other hooks. It packages stateful logic so several components can share it without sharing state — each caller gets its own independent instance.
What is Custom Hooks in React?
A custom hook is a function whose name starts with "use" and which calls other hooks. It packages stateful logic so several components can share it without sharing state — each caller gets its own independent instance.
Why Custom Hooks matters
Custom hooks are React’s answer to code reuse. Fetching, debouncing, localStorage sync, media queries and form handling all become one-line imports instead of copy-pasted effects.
Custom Hooks example
import { useState, useEffect } from 'react';
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
// usage — identical to useState
const [city, setCity] = useLocalStorage('city', 'Pune');How this works
The lazy initialiser reads storage once rather than on every render, the try/catch survives private-browsing restrictions, and returning a [value, setter] pair makes the hook feel like built-in React.
useDebounce — delay a fast-changing value
export function useDebounce(value, delay = 400) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
// only fires a search 400ms after typing stops
const query = useDebounce(input);Key points to remember
- The name must start with "use" — this is how the linter knows to apply the rules of hooks.
- Two components calling the same hook get separate state; hooks share logic, not data.
- Return whatever shape is clearest: an array for a state-like pair, an object for several named values.
Common mistakes with Custom Hooks
- Naming it getLocalStorage instead of useLocalStorage, which disables lint checks.
- Expecting two components using the same hook to share one value — they do not. Use context for that.
React Custom Hooks— Interview Questions & FAQs
Do two components using the same custom hook share state?+
No. Each call creates its own independent state. Custom hooks reuse logic, not data — to share one value across components use context or a state library.
