React · Lesson 10 of 15 · 3 min
Building Reusable Logic with Custom Hooks
This is how you show an interviewer you can write clean, non-repetitive React code.
When to extract logic into a custom hook
If you find yourself copying and pasting useState and useEffect blocks between components, that's your signal. The logic is reusable, so extract it.
A custom hook is just a JavaScript function whose name starts with use and that calls other hooks. It lets you bundle up related state, effects, and callbacks. This separates concerns: your component focuses on rendering the UI, and the hook focuses on managing the behavior.
The trap: Don't over-engineer. If a piece of logic doesn't use any hooks (useState, useEffect, etc.), it's just a regular utility function. Don't call it a hook. An interviewer might ask you to justify the choice, and "it uses state" is the right answer.
How hooks share logic, not state
This is the most critical concept to get right. When two components use the same custom hook, they are sharing the logic, but they are not sharing the state. Each call to a custom hook creates an independent, isolated state instance for the component that called it.
One component's state changes will not affect the other's. This is by design. If you need to share state between components, you'll use other patterns like lifting state up or the Context API.
A real-world example: useLocalStorage
In an interview, you might be asked to build a hook that syncs a component's state with the browser's localStorage. This is a great test because it combines state management (useState), side effects (useEffect), and interaction with a browser API that can fail.
Here is a clean, production-ready implementation.
import { useState, useEffect } from 'react';
export function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] {
// Use a function for the initial state. This ensures localStorage is
// read only once on the initial render, not on every re-render.
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(`Error reading localStorage key “${key}”:`, error);
return initialValue;
}
});
// This effect runs whenever the stored value or the key changes.
// It persists the current state back into localStorage.
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error(`Error setting localStorage key “${key}”:`, error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
This hook's API is identical to useState, making it a seamless replacement. The lazy initializer for useState is an important performance detail. The try...catch blocks show you're thinking about edge cases, like private browsing mode where localStorage access might be blocked.
Answering the "Why hooks?" question
Your ability to articulate trade-offs is as important as your ability to code. Custom hooks are the modern standard for logic reuse in React, largely replacing older patterns.
Interviewer: "When would you use a custom hook over a Higher-Order Component or Render Prop?"
Your answer: "I'd almost always prefer a custom hook for sharing stateful logic. Hooks are just functions, so they're simpler to write, read, and test. They avoid the 'wrapper hell' of nested HOCs and make it explicit where the state and logic are coming from. HOCs can still be useful for purely presentational concerns, like injecting styles or props without involving state, but for behavior, hooks are the idiomatic choice."
The trap: Forgetting effect cleanup. For any useEffect that sets up a subscription, timer, or event listener (like window.addEventListener), you must return a cleanup function. Forgetting this creates memory leaks. The useLocalStorage hook doesn't need one, but a useWindowSize hook absolutely would.
Another trap: Missing dependencies in useEffect. The array at the end of useEffect tells React when to re-run the effect. If you use a variable from your component's scope inside the effect but don't list it in the dependency array, your effect will run with a stale value from a previous render. The eslint-plugin-react-hooks package is essential for catching these bugs automatically.
Try it
Implement a useDebounce hook. It should take a value and a delay (e.g., 500ms) and return a new value that only updates after the original value has stopped changing for the specified delay. This is a classic interview problem and is used constantly in real applications for things like search-as-you-type inputs.
Next: Now that you can organize logic, we'll focus on making it fast in Performance Optimization with Memoization.
Lock it in — apply this lesson under interview conditions.