From 5ef868ec4dea43fa3f4a9e77afdf6f9ec57834cd Mon Sep 17 00:00:00 2001 From: Nick Prat Date: Tue, 27 Feb 2024 14:16:55 -0500 Subject: [PATCH] Added ability to pass function with more then 1 parameter to useDebounce, also added useDebouncedValue --- packages/utils/hooks/useDebounce/index.ts | 25 +++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/packages/utils/hooks/useDebounce/index.ts b/packages/utils/hooks/useDebounce/index.ts index 33619086..7ca1b0b9 100644 --- a/packages/utils/hooks/useDebounce/index.ts +++ b/packages/utils/hooks/useDebounce/index.ts @@ -1,11 +1,11 @@ 'use client' -import { useEffect, useRef } from 'react' +import { useEffect, useState, useRef } from 'react' import debounce from 'lodash/debounce' -const useDebounce = any>( - functionToDebounce: T, +const useDebounce = ( + functionToDebounce: (...params: T) => U, { debounceTime = 400 } = {}, ) => { const debouncedFuncRef = useRef(debounce(functionToDebounce, debounceTime, { trailing: true })) @@ -20,4 +20,21 @@ const useDebounce = any>( return { debouncedFunction: debouncedFuncRef.current } } -export default useDebounce +const useDebouncedValue = (value: T, debounceTime: number) => { + const [debouncedValue, setDebouncedValue] = useState(value) + + useEffect(() => { + const handler = setTimeout(() => { + setDebouncedValue(value) + }, debounceTime) + + return () => { + clearTimeout(handler) + } + }, [value, debounceTime]) + + return debouncedValue +} + + +export {useDebounce as default, useDebouncedValue}