React Hooks In DepthLesson 3.5
How to build custom hooks in React
custom hook definition, naming convention, composing built-in hooks, useLocalStorage example, useFetch example, sharing logic without HOC, rules of hooks
Custom Hooks: Reusable Logic
Custom hooks extract reusable stateful logic into a function. Any function that calls built-in hooks and starts with use is a custom hook. This lets you share logic between components without restructuring your tree.
useLocalStorage Hook
import { useState, useEffect } from 'react';
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
function Settings() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return (
<button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
{theme}
</button>
);
}Rules of Hooks
1. Only call hooks at the top level — never inside loops, conditions, or nested functions. 2. Only call hooks from React functions or other custom hooks. These rules ensure React can track hook order correctly across renders. ESLint's react-hooks/rules-of-hooks plugin enforces them automatically.
