Back to snippets

Fetch Data Hook

Snippet Overview

This snippet provides a custom React hook, useFetch, to fetch data from an API in a web application.

Code

import { useState, useEffect } from 'react'; export const useFetch = (url, options) => { const [data, setData] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch(url, options); if (!response.ok) { throw new Error('Network response was not ok'); } const json = await response.json(); setData(json); } catch (error) { setError(error); } finally { setIsLoading(false); } }; fetchData(); }, [url, options]); return { data, isLoading, error }; };

Usage

  • Import and use the useFetch hook within your React components.
  • Provide the API URL and any options required for the fetch request.
  • Access the data, isLoading, and error values returned by the hook to manage API responses and loading states.

Conclusion

The useFetch hook simplifies data fetching in React applications by providing a reusable and efficient solution. It enhances productivity by abstracting away the complexities of asynchronous API requests and handling common scenarios like loading states and error handling.