Since the introduction of React Hooks, custom hooks have become increasingly important for keeping component logic reusable and clean. In this article, we will introduce the basics of how to create a custom hook and some examples that are often used in practice.
What is a custom hook?
A custom hook is a unique function created by combining React’s built-in Hooks (such as useState and useEffect). There is a rule that the name must start with “use” (e.g. useFetch, useWindowSize).
The biggest advantage is that it does not have a UI (appearance), and only the “state” and “logic” can be separated from the component and shared.
Benefits of creating custom hooks
- Code reusability: The same logic can be reused in multiple components.
- Improved readability: By separating complex logic from the component side, the UI code becomes cleaner.
- Ease of testing: Logic parts can be tested independently.
Example 1: useFetch to summarize API communication
The process of retrieving data from the API occurs in various components. Let’s make this a custom hook.
import { useState, useEffect } from 'react';
export const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await fetch(url);
if (!response.ok) throw new Error('Network response was not ok');
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
How to use:
const { data, loading, error } = useFetch('https://api.example.com/users');
This frees the component from loading state and error handling logic, allowing it to focus on building the UI.
Example 2: Get the browser window size useWindowSize
This can be used when you want to know the current screen width on the JavaScript side, such as when implementing responsive design.
import { useState, useEffect } from 'react';
export const useWindowSize = () => {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
const handleResize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
window.addEventListener('resize', handleResize);
handleResize(); // 初期呼び出し
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowSize;
};
Summary
By using custom hooks, React components can focus on their primary role: how to display data, rather than how to process data. If you find yourself writing the same useState and useEffect combinations over and over again, it’s a great time to create a custom hook.

