A custom hook in React is a function that encapsulates state logic, side effects, or any other functionality and returns values or functions to be used within your component's lifecycle. Custom hooks allow you to extract complex behaviour from components, making them more reusable and easier to reason about.
For example, you can create a custom hook called useFetchData that fetches data from an API and stores it in localStorage. This hook can be reused across multiple components, reducing code duplication and improving maintainability.
Here's a basic implementation of such a custom hook:
import { useState, useEffect } from 'react';
function useFetchData(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);
const result = await response.json();
setData(result);
localStorage.setItem('fetchedData', JSON.stringify(result));
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
export default useFetchData;
Top comments (0)