xnimorz / use-debounce

A debounce hook for react
MIT License
2.94k stars 113 forks source link

Value is not debounced when `leading` and `trailing` are both set to true #182

Open nklhtv opened 1 week ago

nklhtv commented 1 week ago

Describe the bug Value is not debounced when leading and trailing are both set to true

Used to work in 10.0.1

To Reproduce

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { useDebounce } from "use-debounce";

function Input({ defaultValue }) {
  const [value, setValue] = useState(defaultValue);
  const [debouncedValue] = useDebounce(value, 5_000, {
    leading: true,
    trailing: true,
  });
  return (
    <div>
      <input
        defaultValue={defaultValue}
        onChange={(e) => setValue(e.target.value)}
      />
      <p>Value: {value}</p>
      <p>Debounced value: {debouncedValue}</p>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Input defaultValue="Hello world" />, rootElement);

Expected behavior

  1. Focus input box
  2. Enter 1234 with 4 separate keystrokes in less than 5 seconds
  3. debouncedValue should be set to 1 instantly
  4. debouncedValue should be set to 1234 after 5 seconds

What actually happens is that debouncedValue is updated on each keystroke.

use-debounce version: 10.0.3

xnimorz commented 5 days ago

Hey @nklhtv ,

Thanks for submitting the request. I plan to land proper fix for isPending status upcoming week, which should fix that version. In the meantime, please, use 10.0.1