Last active
March 11, 2023 13:53
-
-
Save Haraldson/8bdee011b10fdaf746787585a79e91ce to your computer and use it in GitHub Desktop.
Lodash useDebounce React Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react' | |
import { useDebounce } from './use-debounce' | |
const MySearchComponent = props => { | |
const [search, setSearch, { | |
signal, | |
debouncing | |
}] = useDebounce('') | |
const [results, setResults] = useState([]) | |
useEffect(() => { | |
const fetch = async () => { | |
const results = await fetch(`/stuff?search=${search}`) | |
setResults(results) | |
} | |
fetch() | |
}, [signal]) | |
return ( | |
<input | |
value={search} | |
onChange={e => setSearch(e.currentTarget.value)} /> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useCallback } from 'react' | |
import debounce from 'lodash.debounce' | |
export const useDebounce = (defaultValue, delay = 500, options = defaultOptions) => { | |
const [value, setValueImmediately] = useState(defaultValue) | |
const [debouncing, setDebouncing] = useState(false) | |
const [signal, setSignal] = useState(Date.now()) | |
const setValue = useCallback(value => { | |
setValueImmediately(value) | |
setDebouncing(true) | |
triggerUpdate() | |
}, []) | |
const triggerUpdate = useCallback(debounce(() => { | |
setDebouncing(false) | |
setSignal(Date.now()) | |
}, delay, options), []) | |
return [value, setValue, { | |
signal, | |
debouncing | |
}] | |
} | |
const defaultOptions = { leading: false, trailing: true } |
You’re most welcome, @juanpprieto! Obviously it doesn’t handle request responses landing in the wrong order and so on, but it shows how debouncing and controlled inputs can be combined quite elegantly! :)
very elegant 👍
Hi @Haraldson, I really like your solution, thank you for that.
Would it be possible to add a license to this project? I would love to use it in our system.
Cheers :)
Thanks, I really like this solution, pretty neat
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice, thanks for sharing these @Haraldson