React custom hooks
Created By: chatGPT
React custom hooks are a powerful feature that allows you to encapsulate and reuse stateful logic across multiple components. They are JavaScript functions whose names start with 'use' and can call other hooks. Creating a custom hook can help to keep your components clean and promote code reusability. Below is a simple example of creating and using a custom hook.
import { useState, useEffect } from 'react';
const 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 };
};
This custom hook,
useFetch
, takes a URL as an argument and returns an object containing the fetched data, a loading state, and an error state. You can now use this hook in any component to handle data fetching without repeating the code.import React from 'react';
import useFetch from './useFetch';
const MyComponent = () => {
const { data, loading, error } = useFetch('https://api.example.com/data');
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
};
When you invoke
useFetch
within your MyComponent
, it will automatically manage the loading and error states along with the fetched data. This clearly separates your data-fetching logic from the UI concerns, making your component cleaner and easier to maintain.// Example of using the custom hook in a component
export default MyComponent;