npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mattdealsy/use-fetch-hook

v1.1.1

Published

A custom React hook for data fetching

Downloads

9

Readme

Introduction

The useFetch hook is a powerful tool for managing data fetching and caching in React applications. This guide will walk you through how to use the hook effectively in your components.

Installation

To install the useFetch hook, run the following command:

npm i @mattdealsy/use-fetch-hook

Basic Usage

import { useFetch } from "@mattdealsy/use-fetch-hook";

function MyComponent() {
  const { data, isLoading, isFetching, error, refetch, invalidateQuery } =
    useFetch({
      fetchKey: ["uniqueQueryIdentifier"],
      fetchFn: async () => {
        const response = await fetch("https://api.example.com/data");
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      },
      cacheTTL: 5 * 60 * 1000, // 5 minutes
      refetchInterval: 5000, // Refetch every 5 seconds
    });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <pre>{JSON.stringify(data, null, 2)}</pre>
      <button onClick={refetch}>Refetch</button>
      <button onClick={invalidateQuery}>Invalidate Cache</button>
    </div>
  );
}

API Reference

useFetch Options

  • fetchKey: (string | number | object)[] An array that uniquely identifies the query. This is used for caching and deduplication.
  • fetchFn: () => Promise<T> An async function that returns the data for the query.
  • refetchInterval?: number (Optional) Interval in milliseconds to automatically refetch the data.
  • cacheTTL?: number (Optional) Time-to-live for the cache in milliseconds. Defaults to 10 minutes.

useFetch Return Value

  • data: T | undefined The data returned from the fetchFn.
  • isLoading: boolean True if the query is in its initial loading state.
  • isFetching: boolean True if the query is currently fetching data.
  • error: Error | null Any error that occurred during the most recent query.
  • refetch: () => Promise<void> A function to manually trigger a refetch of the query.
  • invalidateQuery: () => void A function to invalidate the current query cache and trigger a refetch.

Advanced Usage

Parameterized Queries

const { data } = useFetch({
  fetchKey: ["user", userId],
  fetchFn: () => fetchUser(userId),
});

Using Refetch Interval

const { data } = useFetch({
  fetchKey: ["autoRefreshData"],
  fetchFn: fetchAutoRefreshData,
  refetchInterval: 5000, // Refetch every 5 seconds
});

Custom Cache TTL

const { data } = useFetch({
  fetchKey: ["customCacheTTL"],
  fetchFn: fetchCustomCacheTTL,
  cacheTTL: 5 * 60 * 1000, // 5 minutes
});

Manual Cache Invalidation

const { invalidateQuery } = useFetch({
  fetchKey: ["userData"],
  fetchFn: fetchUserData,
});

// Later in your code
const handleUserUpdate = () => {
  // Update user data
  invalidateQuery(); // This will clear the cache and refetch
};

Best Practices

  1. Use consistent fetchKey arrays for the same data across your app.
  2. Keep fetchFn functions pure and free of side effects.
  3. Use the refetchInterval option judiciously to avoid unnecessary API calls.
  4. Leverage the isLoading and isFetching states to show appropriate loading indicators.
  5. Handle errors gracefully using the error object.

By following these guidelines and utilizing the full capabilities of the useFetch hook, you can efficiently manage data fetching and state in your React applications.