Part 24: Creating Reusable Custom Hooks
One of the greatest powers of React is the ability to extract component logic into reusable JavaScript functions called Custom Hooks.
1. Custom Hook Conventions
- The function name must start with
use(e.g.,useLocalStorage,useDebounce). This allows React's linter to verify rules of hooks. - Custom hooks can call standard React hooks (
useState,useEffect, etc.). - Each component calling a custom hook gets its own isolated instance of state.
2. Example 1: useLocalStorage
Persist state automatically to the browser's localStorage:
import { useState, useEffect } from 'react';
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn(`Error reading localStorage key "${key}":`, error);
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.warn(`Error writing to localStorage key "${key}":`, error);
}
}, [key, value]);
return [value, setValue];
}
Consuming useLocalStorage:
export default function AppSettings() {
const [theme, setTheme] = useLocalStorage('app_theme', 'light');
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Stored Theme: {theme}
</button>
);
}
3. Example 2: useWindowSize
import { useState, useEffect } from 'react';
export function useWindowSize() {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
const handleResize = () => {
setSize({ width: window.innerWidth, height: window.innerHeight });
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
Key Takeaways
- Custom hooks start with
useand bundle stateful logic for reuse across multiple components. - State inside custom hooks is completely isolated per component instance.
In Part 25, we enter Module 4 to master React Router v6 and Single Page Application navigation!

