Building Custom Hooks in React — Best Practices
The Interview Question
How do you design a custom hook? What are the best practices and common patterns?
Expert Answer
A custom hook is a function that starts with 'use' and calls other hooks internally. The naming convention isn't just cosmetic — React's linter uses it to enforce the rules of hooks. The purpose of custom hooks is to extract reusable stateful logic from components. The key design principles: a custom hook should do one thing well, return only what the consumer needs, and hide implementation details. A well-designed custom hook has a clear contract — you can swap out the implementation without changing the interface. Common patterns include data fetching hooks (useQuery, useFetch), form handling (useForm, useInput), media queries (useMediaQuery), local storage (useLocalStorage), and debounced values (useDebounce).
Key Points to Hit in Your Answer
- Must start with 'use' — this enables lint rules enforcement
- Custom hooks can call other hooks; regular functions cannot
- Design for the consumer: return [value, setter] for simple state, return objects for complex state
- Each call to a custom hook gets its own isolated state
- Test custom hooks with renderHook from @testing-library/react-hooks
Code Example
// useLocalStorage — a practical custom hook
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});
const setValue = (value) => {
const valueToStore = value instanceof Function
? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
};
return [storedValue, setValue];
}
// Usage — same API as useState
const [theme, setTheme] = useLocalStorage('theme', 'dark');
What Interviewers Are Really Looking For
Interviewers want to see that you can identify when logic should be extracted into a hook vs. staying in a component. Show that you think about the consumer API — returning an array vs. object, handling loading/error states, and making the hook testable in isolation.
Practice This Question with AI Grading
Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.
Start Practicing Free →