Example of useFetch() Custom hook in react.js

Example of useFetch() Custom hook in react.js

Here's how to create a useFetch() hook in React for getting data from an API:

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);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
};

export default useFetch;

Now, you can use this useFetch hook in your components to fetch data from an API:

import React from 'react';
import useFetch from './useFetch'; // Assuming you've placed the hook in a separate file

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>
      <h1>Data from API:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default MyComponent;

In this example:

  • We define the MyComponent functional component.

  • We use the useFetch hook to fetch data from the specified URL (https://api.example.com/data in this case).

  • The hook returns an object containing data, loading, and error states.

  • We conditionally render different UI based on the loading and error states.

  • If loading is true, we display a loading message.

  • If an error occurs during fetching, we display an error message.

  • If the data is successfully fetched, we display the fetched data in a pre element.

The useFetch hook simplifies getting data in React components by handling common tasks such as managing loading and error states. It allows for code reuse and keeps components clean and easy to understand.

Did you find this article valuable?

Support LingarajTechhub by becoming a sponsor. Any amount is appreciated!