Skip to content

Instantly share code, notes, and snippets.

@Haraldson
Last active Sep 16, 2021
Embed
What would you like to do?
Lodash useDebounce React Hook
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)} />
)
}
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 }
@juanpprieto
Copy link

juanpprieto commented May 14, 2020

nice, thanks for sharing these @Haraldson

@Haraldson
Copy link
Author

Haraldson commented May 14, 2020

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! :)

@Goldziher
Copy link

Goldziher commented Sep 29, 2020

very elegant 👍

@tfitzke
Copy link

tfitzke commented Jun 1, 2021

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 :)

@efleurine
Copy link

efleurine commented Jul 20, 2021

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