react

Snippets – React Fetch Hook example


This React Fetch hook is created by composing the useState and useEffect hooks.

import React, { useState, useEffect } from "react";

export function useFetch(uri) {
  const [data, setData] = useState();
  const [error, setError] = useState();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!uri) return;
    fetch(uri)
      .then(data => data.json())
      .then(setData)
      .then(() => setLoading(false))
      .catch(setError);
  }, [uri]);

  return {
    loading,
    data,
    error
  };
}

The three states of a fetch request in the above code snippet are:

  • pending – when the request is pending
  • data – data is retrieved successfully
  • Error – something went wrong

These states are managed inside useEffect hook.


Share on social media

//