Home Web Front-end JS Tutorial How to Build a React Hook That Handles Sequential Requests

How to Build a React Hook That Handles Sequential Requests

Aug 21, 2024 am 09:06 AM

When you need to respond quickly to user actions and fetch the latest data from the backend, you might require a React Hook that supports sequential requests. This hook can cancel previous requests if they are still ongoing and only return the most recent data. This not only improves performance but also enhances the user experience.

Building a Simple Sequential Request React Hook

Let’s start by building a simple sequential request React hook:

import { useCallback, useRef } from 'react';
​
const buildCancelableFetch = <T>(
  requestFn: (signal: AbortSignal) => Promise<T>,
) => {
  const abortController = new AbortController();
​
  return {
    run: () =>
      new Promise<T>((resolve, reject) => {
        if (abortController.signal.aborted) {
          reject(new Error('CanceledError'));
          return;
        }
​
        requestFn(abortController.signal).then(resolve, reject);
      }),
​
    cancel: () => {
      abortController.abort();
    },
  };
};
​
function useLatest<T>(value: T) {
  const ref = useRef(value);
  ref.current = value;
  return ref;
}
​
export function useSequentialRequest<T>(
  requestFn: (signal: AbortSignal) => Promise<T>,
) {
  const requestFnRef = useLatest(requestFn);
  const currentRequest = useRef<{ cancel: () => void } | null>(null);
​
  return useCallback(async () => {
    if (currentRequest.current) {
      currentRequest.current.cancel();
    }
​
    const { run, cancel } = buildCancelableFetch(requestFnRef.current);
    currentRequest.current = { cancel };
​
    return run().finally(() => {
      if (currentRequest.current?.cancel === cancel) {
        currentRequest.current = null;
      }
    });
  }, [requestFnRef]);
}

The key idea here comes from the article “How to Annul Promises in JavaScript.” You can use it like this:

import { useSequentialRequest } from './useSequentialRequest';
​
export function App() {
  const run = useSequentialRequest((signal: AbortSignal) =>
    fetch('http://localhost:5000', { signal }).then((res) => res.text()),
  );
​
  return <button onClick={run}>Run</button>;
}

This way, when you click the button quickly multiple times, you will only get the data from the latest request, and previous requests will be discarded.

How to Build a React Hook That Handles Sequential Requests

Building an Optimized Sequential Request React Hook

If we need a more comprehensive sequential request React Hook, there’s room for improvement in the code above. For example:

  • We can defer creating an AbortController until it’s actually needed, reducing unnecessary creation costs.

  • We can use generics to support any type of request arguments.

Here’s the updated version:

import { useCallback, useRef } from 'react';
​
function useLatest<T>(value: T) {
  const ref = useRef(value);
  ref.current = value;
  return ref;
}
​
export function useSequentialRequest<Args extends unknown[], Data>(
  requestFn: (signal: AbortSignal, ...args: Args) => Promise<Data>,
) {
  const requestFnRef = useLatest(requestFn);
​
  const running = useRef(false);
  const abortController = useRef<AbortController | null>(null);
​
  return useCallback(
    async (...args: Args) => {
      if (running.current) {
        abortController.current?.abort();
        abortController.current = null;
      }
​
      running.current = true;
​
      const controller = abortController.current ?? new AbortController();
      abortController.current = controller;
​
      return requestFnRef.current(controller.signal, ...args).finally(() => {
        if (controller === abortController.current) {
          running.current = false;
        }
      });
    },
    [requestFnRef],
  );
}

Note that in the finally block, we check whether the current controller equals abortController.current to prevent race conditions. This ensures that only the active request can modify the running state.

More Comprehensive Usage:

import { useState } from 'react';
import { useSequentialRequest } from './useSequentialRequest';
​
export default function Home() {
  const [data, setData] = useState('');
​
  const run = useSequentialRequest(async (signal: AbortSignal, query: string) =>
    fetch(`/api/hello?query=${query}`, { signal }).then((res) => res.text()),
  );
​
  const handleInput = async (queryStr: string) => {
    try {
      const res = await run(queryStr);
      setData(res);
    } catch {
      // ignore errors
    }
  };
​
  return (
    <>
      <input
        placeholder="Please input"
        onChange={(e) => {
          handleInput(e.target.value);
        }}
      />
      <div>Response Data: {data}</div>
    </>
  );
}

You can try it online: as you type quickly, the previous requests will be canceled, and only the latest response will be shown.

How to Build a React Hook That Handles Sequential Requests


If you found this helpful, please consider subscribing to my newsletter for more useful articles and tools about web development. Thanks for reading!

The above is the detailed content of How to Build a React Hook That Handles Sequential Requests. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Advanced Conditional Types in TypeScript Advanced Conditional Types in TypeScript Aug 04, 2025 am 06:32 AM

TypeScript's advanced condition types implement logical judgment between types through TextendsU?X:Y syntax. Its core capabilities are reflected in the distributed condition types, infer type inference and the construction of complex type tools. 1. The conditional type is distributed in the bare type parameters and can automatically split the joint type, such as ToArray to obtain string[]|number[]. 2. Use distribution to build filtering and extraction tools: Exclude excludes types through TextendsU?never:T, Extract extracts commonalities through TextendsU?T:Never, and NonNullable filters null/undefined. 3

Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Aug 05, 2025 am 08:30 AM

This article explores in-depth how to automatically generate solveable puzzles for the Double-Choco puzzle game. We will introduce an efficient data structure - a cell object based on a 2D grid that contains boundary information, color, and state. On this basis, we will elaborate on a recursive block recognition algorithm (similar to depth-first search) and how to integrate it into the iterative puzzle generation process to ensure that the generated puzzles meet the rules of the game and are solveable. The article will provide sample code and discuss key considerations and optimization strategies in the generation process.

What is the class syntax in JavaScript and how does it relate to prototypes? What is the class syntax in JavaScript and how does it relate to prototypes? Aug 03, 2025 pm 04:11 PM

JavaScript's class syntax is syntactic sugar inherited by prototypes. 1. The class defined by class is essentially a function and methods are added to the prototype; 2. The instances look up methods through the prototype chain; 3. The static method belongs to the class itself; 4. Extends inherits through the prototype chain, and the underlying layer still uses the prototype mechanism. Class has not changed the essence of JavaScript prototype inheritance.

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce` Mastering JavaScript Array Methods: `map`, `filter`, and `reduce` Aug 03, 2025 am 05:54 AM

JavaScript's array methods map, filter and reduce are used to write clear and functional code. 1. Map is used to convert each element in the array and return a new array, such as converting Celsius to Fahrenheit; 2. Filter is used to filter elements according to conditions and return a new array that meets the conditions, such as obtaining even numbers or active users; 3. Reduce is used to accumulate results, such as summing or counting frequency, and the initial value needs to be provided and returned to the accumulator; none of the three modify the original array, and can be called in chain, suitable for data processing and conversion, improving code readability and functionality.

How can you remove a CSS class from a DOM element using JavaScript? How can you remove a CSS class from a DOM element using JavaScript? Aug 05, 2025 pm 12:51 PM

The most common and recommended method for removing CSS classes from DOM elements using JavaScript is through the remove() method of the classList property. 1. Use element.classList.remove('className') to safely delete a single or multiple classes, and no error will be reported even if the class does not exist; 2. The alternative method is to directly operate the className property and remove the class by string replacement, but it is easy to cause problems due to inaccurate regular matching or improper space processing, so it is not recommended; 3. You can first judge whether the class exists and then delete it through element.classList.contains(), but it is usually not necessary; 4.classList

Vercel SPA routing and resource loading: Solve deep URL access issues Vercel SPA routing and resource loading: Solve deep URL access issues Aug 13, 2025 am 10:18 AM

This article aims to solve the problem of deep URL refresh or direct access causing page resource loading failure when deploying single page applications (SPAs) on Vercel. The core is to understand the difference between Vercel's routing rewriting mechanism and browser parsing relative paths. By configuring vercel.json to redirect all paths to index.html, and correct the reference method of static resources in HTML, change the relative path to absolute path, ensuring that the application can correctly load all resources under any URL.

Vercel Single Page Application (SPA) Deployment Guide: Solving Deep URL Asset Loading Issues Vercel Single Page Application (SPA) Deployment Guide: Solving Deep URL Asset Loading Issues Aug 13, 2025 pm 01:03 PM

This tutorial aims to solve the problem of loading assets (CSS, JS, images, etc.) when accessing multi-level URLs (such as /projects/home) when deploying single page applications (SPAs) on Vercel. The core lies in understanding the difference between Vercel's routing rewriting mechanism and relative/absolute paths in HTML. By correctly configuring vercel.json, ensure that all non-file requests are redirected to index.html and correcting asset references in HTML as absolute paths, thereby achieving stable operation of SPA at any depth URL.

JavaScript Performance Optimization: Beyond the Basics JavaScript Performance Optimization: Beyond the Basics Aug 03, 2025 pm 04:17 PM

OptimizeobjectshapesbyinitializingpropertiesconsistentlytomaintainhiddenclassesinJavaScriptengines.2.Reducegarbagecollectionpressurebyreusingobjects,avoidinginlineobjectcreation,andusingtypedarrays.3.Breaklongtaskswithasyncscheduling,usepassiveeventl

See all articles