Skip to content

Commit

Permalink
improve use-filter hook to only run on change (and not on first rende…
Browse files Browse the repository at this point in the history
…r anymore)
  • Loading branch information
lukasvice committed Feb 7, 2024
1 parent d3f1aae commit 958665b
Showing 1 changed file with 18 additions and 19 deletions.
37 changes: 18 additions & 19 deletions src/components/filter/useFilter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useDebounce } from '@aboutbits/react-toolbox'
import {
ChangeEventHandler,
ChangeEvent,
useCallback,
useEffect,
useMemo,
Expand Down Expand Up @@ -39,30 +38,30 @@ export function useFilter<TElement extends HTMLElement & { value: unknown }>() {
}, [])

const settingNewValueRef = useRef(false)

const [internalValue, setInternalValue] = useState(value)
const debouncedInternalValue = useDebounce(internalValue, debounceInterval)
const oldDebouncedInternalValueRef = useRef<TValue>()

useEffect(() => {
// Check that the debounced value is new, because `setValue` might not be reference stable and trigger this effect even though the debounced value did not change
if (debouncedInternalValue !== oldDebouncedInternalValueRef.current) {
oldDebouncedInternalValueRef.current = debouncedInternalValue
setValue(debouncedInternalValue)
settingNewValueRef.current = false
}
}, [debouncedInternalValue, setValue])
const timeoutRef = useRef<NodeJS.Timeout | null>(null)

useEffect(() => {
if (element && !settingNewValueRef.current) {
element.value = value
}
}, [value, element])

const onChange: ChangeEventHandler<TElement> = (e) => {
settingNewValueRef.current = true
setInternalValue(e.target.value as TValue)
}
const onChange = useCallback(
(e: ChangeEvent<TElement>) => {
settingNewValueRef.current = true

if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
timeoutRef.current = null
}

timeoutRef.current = setTimeout(() => {
setValue(e.target.value as TValue)
settingNewValueRef.current = false
}, debounceInterval)
},
[debounceInterval, setValue],
)

return {
ref: elementRef,
Expand Down

0 comments on commit 958665b

Please sign in to comment.