
Day 13: Mastering Custom Hooks in React
By now, we’ve covered important built-in React Hooks like useState
, useEffect
, useRef
, and useReducer
. Each of them serves a specific purpose and makes React more powerful.
But sometimes, as projects grow, you may notice repeated logic in multiple components. Instead of duplicating code, React allows us to create Custom Hooks.
👉 In this blog, we’ll learn what Custom Hooks in React are, why they’re useful, and how to build them step by step.
What are Custom Hooks in React?
Custom Hooks in React are user-defined functions that start with the prefix "use"
and allow you to reuse stateful logic across different components.
- They are not built-in hooks but are built using existing React hooks.
- They don’t add new features to React but allow you to organize and share logic.
- A Custom Hook must always follow the Rules of Hooks (called only inside React functions, never inside loops/conditions).
Why Use Custom Hooks in React?
- Reusability – Write logic once and use it in multiple components.
- Clean Code – Separate business logic from UI rendering.
- Maintainability – Easy to update and fix bugs since logic is centralized.
- Better Organization – Your components stay small and focused.
Example 1: A useLocalStorage Custom Hook
Let’s create a simple custom hook to handle localStorage.
import { useState, useEffect } from "react";
// Custom Hook: useLocalStorage
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
export default useLocalStorage;
How to use it
import React from "react";
import useLocalStorage from "./useLocalStorage";
function ThemeSwitcher() {
const [theme, setTheme] = useLocalStorage("theme", "light");
return (
<div className="p-4">
<h2 className="text-lg font-bold mb-2">Custom Hooks in React Example</h2>
<p>Current Theme: {theme}</p>
<button
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
className="px-3 py-2 bg-blue-500 text-white rounded"
>
Toggle Theme
</button>
</div>
);
}
export default ThemeSwitcher;
With this custom hook, any component can easily use persistent state via localStorage
without duplicating logic.
Example 2: A useWindowWidth Custom Hook
Sometimes you may need to check the screen size to adjust UI. Instead of writing the same event listeners again and again, we can use a custom hook.
import { useState, useEffect } from "react";
// Custom Hook: useWindowWidth
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}
export default useWindowWidth;
How to use it
import React from "react";
import useWindowWidth from "./useWindowWidth";
function ResponsiveComponent() {
const width = useWindowWidth();
return (
<div className="p-4">
<h2 className="text-lg font-bold mb-2">Responsive Component</h2>
<p>Window width: {width}px</p>
{width < 600 ? (
<p>Mobile View</p>
) : (
<p>Desktop View</p>
)}
</div>
);
}
export default ResponsiveComponent;
This hook now handles screen resizing in any component, keeping logic separate and reusable.
Best Practices for Custom Hooks in React
- Always prefix the hook name with
use
(e.g.,useAuth
,useFetch
). - Keep them focused on one task.
- Extract logic only when it’s reused across multiple components.
- Follow React Hook rules (call hooks only at the top level of a component or another hook).
🔗 Official Docs: Custom Hooks in React
Wrapping Up
Today, we learned:
- What Custom Hooks in React are.
- Why they are useful for reusing logic.
- Examples:
useLocalStorage
anduseWindowWidth
. - Best practices for writing your own hooks.
👉 In the next blog (Day 14), we’ll explore the Context API in React and see how it helps us avoid prop drilling and manage global state.