How to create Custom Hooks in React
Custom hooks are a powerful feature in React that allow you to reuse logic across components. They are functions that start with the word use
and can call other hooks if needed.
Creating a Custom Hook
To create a custom hook, you need to follow these rules:
- The function name must start with
use
. - The function can call other hooks if needed.
- The function can accept arguments to customize its behavior.
- The function must return an array or object with the values you want to expose.
Example: useFetch
Let’s create a custom hook called useFetch
that fetches data from an API.
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
setData(result);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
export default useFetch;
Example of usage
import React from 'react';
import useFetch from './useFetch';
function App() {
const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/posts');
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>Posts</h1>
<ul>
{data && data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
export default App;