useDebounce 简单有效的react防抖动方案

Published on Aug. 22, 2023, 12:11 p.m.

安装

yarn add use-debounce
# or
npm i use-debounce --save

hook方式使用

import React, { useState } from 'react';
import { useDebounce } from 'use-debounce';

export default function Input() {
  const [text, setText] = useState('Hello');
  const [value] = useDebounce(text, 1000);

  return (
    <div>
      <input
        defaultValue={'Hello'}
        onChange={(e) => {
          setText(e.target.value);
        }}
      />
      <p>Actual value: {text}</p>
      <p>Debounce value: {value}</p>
    </div>
  );
}

示例

use-debounce
Simple usage: https://codesandbox.io/s/kx75xzyrq7

Debounce HTTP request: https://codesandbox.io/s/rr40wnropq

Debounce HTTP request with leading param: https://codesandbox.io/s/cache-example-with-areas-and-leading-param-119r3i

use-debounce callback
Simple usage: https://codesandbox.io/s/x0jvqrwyq

Combining with native event listeners: https://codesandbox.io/s/32yqlyo815

Cancelling, maxWait and memoization: https://codesandbox.io/s/4wvmp1xlw4

HTTP requests: https://codesandbox.io/s/use-debounce-callback-http-y1h3m6

<iframe src=”https://codesandbox.io/embed/kx75xzyrq7?fontsize=14&hidenavigation=1&theme=dark
style=”width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;”
title=”cache”
allow=”accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking”
sandbox=”allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts”

Debounced callbacks 使用

import { useDebouncedCallback } from 'use-debounce';

function Input({ defaultValue }) {
  const [value, setValue] = useState(defaultValue);
  // Debounce callback
  const debounced = useDebouncedCallback(
    // function
    (value) => {
      setValue(value);
    },
    // delay in ms
    1000
  );

  // you should use `e => debounced(e.target.value)` as react works with synthetic events
  return (
    <div>
      <input defaultValue={defaultValue} onChange={(e) => debounced(e.target.value)} />
      <p>Debounced value: {value}</p>
    </div>
  );
}

项目主页:
https://github.com/xnimorz/use-debounce

Tags: