React Custom Hook for API

javascript
#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 };
};

πŸ’¬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