Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve use-filter hook to run only on change (and not on first render anymore) #307

Merged
merged 1 commit into from
Feb 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading