Skip to content

useDebouncedState

This hook returns a state that Updates its value after a specific delay to handle fast updated values.

Parameters

  1. the initial state value.
  2. and the debouce options:
NameTypeDescription
delayNumberthe duration before updating the state in ms (default is 500).

Return Values

It returns a tuple of 3 values:

IndexNameTypeDescription
0debouncedValueAnythe current debounced value.
1setValueFunctionupdates the value.
2valueAnythe actual current value (not debounced).

TIP

You can also get a debounced value from an external state by setting it as the initial value:

ts
...
const [value, setValue] = useState('anything');
const [debounced] = useDebouncedState(value, { delay: 500 });
...
...
const [value, setValue] = useState('anything');
const [debounced] = useDebouncedState(value, { delay: 500 });
...

Example Usage

tsx
import { useDebouncedState } from 'react-pre-hooks';

export default function Example() {
  const [debounced, setText, current] = useDebouncedState('Hello', { delay: 400 });

  return (
    <main>
      <input type="text" value={current} onChange={e => setText(e.target.value)} />
      <div>Current text: {current}</div>
      <div>Debounced text: {debounced}</div>
    </main>
  );
}
import { useDebouncedState } from 'react-pre-hooks';

export default function Example() {
  const [debounced, setText, current] = useDebouncedState('Hello', { delay: 400 });

  return (
    <main>
      <input type="text" value={current} onChange={e => setText(e.target.value)} />
      <div>Current text: {current}</div>
      <div>Debounced text: {debounced}</div>
    </main>
  );
}

Released under the MIT License.