0
const [query,setQuery] = useState<string>('')

useEffect(() => {
    dispatch(postQuery(query))
},
[query])

<input value={query} onChange={e => setQuery(e.currentTarget.value)}/>

I need that my useEffect wait N seconds while data is changing, when this data was changed and is not changing for N seconds it will be triggered. How to properly do it ?

  • 1
    What you want is called "Debounce" there are many questions / answers about it on stackoverflow, here is one answer that will probably work for you: https://stackoverflow.com/a/72672732/4364635 – Jacob Smit Nov 03 '22 at 03:48

1 Answers1

1

There are two approaches to make this happen (debounce):

  • You can either use a npm package use-debounce OR

  • You can use a easy approach using react hooks if you don't want to increase a dependency.

const [query,setQuery] = useState<string>('')

useEffect(() => {

  //causes delay in performing the dispatch
  const delayFunction = setTimeout(() => {
    if (searchTerm) {
       dispatch(postQuery(query))
    }
  }, 400)
  
  return () => clearTimeout(delayFunction)

}, [query])

<input value={query} onChange={e => setQuery(e.currentTarget.value)}/>

Hope this helps you out :)

Meet Bhalodiya
  • 630
  • 7
  • 25