Custom Hooks in React
Introduction
As React applications grow, you may notice that some logic is repeated across multiple components. For example, fetching data, handling form inputs, or tracking window size may appear in different places. To avoid duplicating code, React allows you to create custom hooks.
Custom hooks help you reuse logic in a clean and organized way while still using React’s built-in hooks like useState and useEffect.
What Is a Custom Hook?
A custom hook is simply a JavaScript function whose name starts with "use" and that can call other hooks inside it. Custom hooks allow you to extract component logic into reusable functions.
They do not change how React works — they just make code easier to share and maintain.
Creating a Simple Custom Hook
Here’s an example of a custom hook that tracks a counter value.
import { useState } from "react";
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return { count, increment, decrement };
}
This hook manages counter logic and returns values and functions.
Using a Custom Hook in a Component
function CounterComponent() {
const { count, increment, decrement } = useCounter(5);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>Increase</button>
<button onClick={decrement}>Decrease</button>
</div>
);
}
The component stays clean because logic is separated into the hook.
Example: Fetching Data with a Custom Hook
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
This hook can now be reused wherever data fetching is needed.
Benefits of Custom Hooks
Reuse logic across components
Keep components clean and focused on UI
Improve code readability and maintainability
Separate business logic from presentation
Rules for Custom Hooks
Custom hooks follow the same rules as React hooks:
Only call hooks at the top level
Only call hooks inside React functions or custom hooks
The hook name must start with "use"
Common Mistakes to Avoid
Calling hooks inside conditions or loops
Forgetting dependency arrays in useEffect inside hooks
Treating custom hooks like regular functions without following hook rules
Summary
In this chapter, you learned how custom hooks help reuse logic across React components. You created simple and advanced custom hooks, used them inside components, and understood their benefits and rules. Custom hooks make large React applications more modular and easier to maintain.