UNPKG

react-exo-hooks

Version:

A collection of useful hooks for data structures and logic, designed for efficiency

20 lines (19 loc) 651 B
import { useEffect, useState } from 'react'; const DEFAULT_TIMEOUT_MS = 1000; /** * Debounced setState * @param initial The initial state value * @param timeoutMs The debounce interval * @returns [state, setState, real] */ export function useDebouncedState(initial, timeoutMs = DEFAULT_TIMEOUT_MS) { const [debounced, setDebounced] = useState(initial); const [real, setReal] = useState(initial); useEffect(() => { const timeout = setTimeout(() => { setDebounced(real); }, timeoutMs); return () => clearTimeout(timeout); }, [real, timeoutMs]); return [debounced, setReal, real]; }