Skip to content

Instantly share code, notes, and snippets.

@tungvn
Created December 26, 2025 04:22
Show Gist options
  • Select an option

  • Save tungvn/e96b5cd2426b0bb384235d255d0483fc to your computer and use it in GitHub Desktop.

Select an option

Save tungvn/e96b5cd2426b0bb384235d255d0483fc to your computer and use it in GitHub Desktop.
How to use React.useCallback with debounce/throttle?
import React from 'react'
import debounce from 'lodash/debounce' // Or throttle
export const HelloWorld: React.FC = () => {
// Example for a state can change quickly in a bit of time
const [innerParams, setInnerParams] = React.useState<string>('')
// Use ref to create a freeze debounce function to make sure it's not rerender
// Need to pass the changing parameters here
const fetch = React.useRef(debounce((params: any) => {
// do stuff with params
}, 300))
// Listen the changes and trigger debounce method, it will call a lot at here,
// but the debounce will do correct approach
useEffect(() => {
const debounced = fetch.current(innerParams)
return () => {
debounced.cancel()
}
}, [innerParams])
return <input value={innerParams} onChange={setInnerParams} />
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment