React Custom Hooks Explained — Reusable Logic Extraction
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about React Custom Hooks Explained. We cover key concepts, practical examples, and best practices to help you master this topic.
React custom hooks are JavaScript functions that use other React hooks to encapsulate reusable stateful logic, following the naming convention useSomething.
What You'll Learn
- How to create a custom hook
- How to compose hooks together
- How to handle parameters and return values
- When to extract a custom hook
- Testing custom hooks
Why It Matters
Custom hooks let you share stateful logic between components without changing the component hierarchy. They are the primary mechanism for code reuse in modern React.
import { useState, useEffect, useCallback } from "react";
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});
const setValue = useCallback((value) => {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
localStorage.setItem(key, JSON.stringify(valueToStore));
}, [key, storedValue]);
return [storedValue, setValue];
}
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;
}
// Usage
function SettingsPage() {
const [theme, setTheme] = useLocalStorage("theme", "light");
const size = useWindowSize();
return (
<div>
<p>Window: {size.width}x{size.height}</p>
<button onClick={() => setTheme(t => t === "light" ? "dark" : "light")}>
Theme: {theme}
</button>
</div>
);
}
Expected output: Theme persisted in localStorage, window size tracked, both as reusable custom hooks.
← Previous
React Axios Explained — HTTP Client for React Apps
Next →
React Hooks Rules Explained — The Rules of Hooks
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro