React Custom Hook for API
#custom-hooks
π€cs
π
Last updated 18 days ago
πΉ Overview
React custom hooks help separate data fetching logic from UI components, keeping them clean and reusable.
πΉ Concept
Custom hooks are just normal JavaScript functions that use Reactβs built-in hooks (useState, useEffect) internally.
π»Source Code
import { useState, useEffect } from 'react';
/**
* Custom hook to fetch data from an API endpoint.
*/
export const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false;
async function fetchData() {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Network response was not ok');
const result = await response.json();
if (!ignore) setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchData();
return () => { ignore = true }; // cleanup on unmount
}, [url]);
return { data, loading, error };
};πRelated Snippets
Similar code snippets you might find interesting
π¬Comments (0)
πPlease login to post comments
π¬
No comments yet. Be the first to share your thoughts!
β‘Actions
Share this snippet:
π€About the Author
c
cs
Active contributor
