Skip to content
A React custom hook for Fetch API
JavaScript
Branch: master
Clone or download
Latest commit def51bd Jul 7, 2019

README.md

react-hooks-fetch

Build Status npm version bundle size

A React custom hook for Fetch API

Important notes

If you are just looking for React hooks for Fecth API, please visit https://github.com/dai-shi/react-hooks-async, which is a more stable library that includes useFetch.

This is an experimental library trying to combine Fetch and Suspense, and it is not meant for production.

History

This library has been changed over time. Here's the list of various implementations.

Install

npm install react-hooks-fetch

Usage

import React, { Suspense } from 'react';
import { useFetch } from 'react-hooks-fetch';

const DisplayRemoteData = () => {
  const { error, data } = useFetch('http://...');
  if (error) return <span>Error: {error.message}</span>;
  if (!data) return null; // this is important
  return <span>RemoteData: {data}</span>;
};

const App = () => (
  <Suspense fallback={<span>Loading...</span>}>
    <DisplayRemoteData />
  </Suspense>
);

Examples

The examples folder contains working examples. You can run one of them with

PORT=8080 npm run examples:minimal

and open http://localhost:8080 in your web browser.

You can also try them in codesandbox.io: 01 02 03 04 05

Blogs

Limitations

  • Suspense is only for lazy loading in React 16.8 and this library uses an undocumented behavior of Suspense.
  • This library does not offer any caching mechanism. There are some use cases where caching is not important but cancellation is important. Note that the browser cache is still effective.
You can’t perform that action at this time.