Skip to content

Instantly share code, notes, and snippets.

@Haraldson
Last active March 11, 2023 13:53
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Haraldson/8bdee011b10fdaf746787585a79e91ce to your computer and use it in GitHub Desktop.
Save Haraldson/8bdee011b10fdaf746787585a79e91ce to your computer and use it in GitHub Desktop.
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 }
@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

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