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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@mdus/use-http-request-hook

v1.0.2

Published

A production-ready React hook for making HTTP requests with built-in GET caching, debounce support, waterfall protection, and AbortController cancellation.

Downloads

21

Readme

useHttpRequest

A lightweight, production-ready React hook for making HTTP requests — with:

  • ✅ Built-in GET request caching
  • Waterfall protection for shared concurrent requests
  • ✅ Native AbortController handling
  • ✅ Optional debounce delay
  • ✅ Easy refetch and manual cache invalidation
  • ✅ Zero dependencies — just fetch and idiomatic React

Why Use This Hook?

No more boilerplate, stale fetches, or duplicate network calls.

useHttpRequest is for React developers who want:

  • Clean async logic without useEffect gymnastics
  • Reliable loading/error/data state without manual tracking
  • Built-in caching and request deduplication (waterfall protection)
  • Auto-abort behavior to prevent memory leaks
  • Full support for GET, POST, PUT, DELETE, and custom configs

Perfect for:

  • Fetching data on mount
  • Debounced APIs (e.g., search/autocomplete)
  • Avoiding redundant GET calls in multiple components
  • Keeping UI state clean, responsive, and React-idiomatic

What Is This?

useHttpRequest() is a custom React hook that simplifies fetch() logic inside functional components.

It handles:

  • What to fetch (url)
  • How to fetch (method, headers, body)
  • When to fetch (with debounce and cleanup)
  • What to do with the result (data, error, isLoading)

You use it like this:

const { data, error, isLoading, refetch } = useHttpRequest(url, options);

Installation

npm install @mdus/use-http-request-hook
# or
yarn add @mdus/use-http-request-hook

API Reference

What It Expects

| Argument | Type | Required | Description | | --------- | -------- | -------- | ------------------------------------------- | | url | string | ✅ Yes | The URL or endpoint to fetch data from | | options | object | ❌ No | An optional object to configure the request |

What Goes Inside options

| Option | Type | Default | Description | | ---------- | -------- | ------- | --------------------------------------------------------- | | method | string | "GET" | HTTP method ("GET", "POST", "PUT", "DELETE" etc.) | | headers | object | {} | Any custom headers (Content-Type, auth tokens, etc.) | | body | object | null | Payload for non-GET requests (automatically stringified) | | debounce | number | 0 | Delay in milliseconds before the request is sent |

What It Returns

| Key | Type | Description | | ----------- | ---------- | ---------------------------------------------------- | | data | any | The JSON response from the API (or null initially) | | isLoading | boolean | true while request is in progress | | error | string | Error message if something goes wrong | | refetch | function | Manually re-trigger the request |


Examples

1. Simple GET Request

import useHttpRequest from "@mdus/use-http-request-hook";

function Products() {
  const { data, isLoading, error } = useHttpRequest("https://fakestoreapi.com/products");

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

  return (
    <ul>
      {data?.map((item) => (
        <li key={item.id}>{item.title}</li>
      ))}
    </ul>
  );
}

2. POST Request with JSON Body

const { data, error, isLoading } = useHttpRequest("https://api.example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: {
    name: "Alice",
    email: "[email protected]"
  }
});

3. Debounced GET Request (e.g., Search Input)

const { data, isLoading } = useHttpRequest(`https://api.com/search?q=${query}`, {
  debounce: 500 // Waits 500ms after typing stops
});

4. Manual Refetch

const { data, refetch } = useHttpRequest("https://api.com/stats");

<button onClick={refetch}>Refresh Data</button>

Advanced Features

GET Caching

  • Only GET requests are cached by default
  • Cached in memory (not persisted to disk)
  • Avoids repeat requests during a session
// Will use cache if already fetched:
useHttpRequest("https://api.com/items");

Waterfall Protection

Multiple components requesting the same GET URL won't duplicate the request:

// Component A
useHttpRequest("https://api.com/profile");

// Component B  
useHttpRequest("https://api.com/profile");

// ✅ Only one fetch will actually run — both use same in-flight promise

Manual Cache Control

import { clearCache, invalidateURL } from "@mdus/use-http-request-hook";

clearCache(); // Wipe all cached GET responses
invalidateURL("https://api.com/products"); // Clear just one

How It Works (Beginner-Friendly Flow)

  1. You call useHttpRequest(url, options)
  2. The hook checks if this is a GET request and already cached
  3. If not cached, it creates a fetch() request with AbortController
  4. While the request is in progress, isLoading is true
  5. If successful, data is filled and cached (for GET only)
  6. If there's an error, it shows up in error
  7. If component unmounts or URL changes, the request is safely aborted

Auto Cleanup

  • Cancels in-progress requests if:
    • Component unmounts
    • URL or options change
  • Prevents memory leaks or setting state on an unmounted component

How It Works Internally

  • Uses native fetch() with AbortController for safety
  • GET responses cached in a Map (session memory)
  • In-flight GET requests tracked in another Map to prevent waterfall issues
  • Uses setTimeout for debouncing and cleans up on unmount
  • React useRef, useCallback, and useMemo ensure stability across renders

File Structure

use-http-request-hook/
├── src/
│   └── useHttpRequest.js
├── dist/
│   └── index.js
├── package.json
└── README.md

Author

Md Umar Siddique


License

MIT © 2025 Md Umar Siddique


Final Note

This hook is designed to solve real problems React developers face every day — while staying small, composable, and dependency-free. It's a reflection of production-level thinking: eliminating duplication, managing edge cases, and creating a smoother dev experience.

If it helps you, feel free to star, use, and share.