Created
December 26, 2025 04:22
-
-
Save tungvn/e96b5cd2426b0bb384235d255d0483fc to your computer and use it in GitHub Desktop.
How to use React.useCallback with debounce/throttle?
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 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