middleStackoverflower
middleStackoverflower

Reputation: 262

How to not trigger useEffect for N seconds while data changing?

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 ?

Upvotes: 0

Views: 48

Answers (1)

Meet Bhalodiya
Meet Bhalodiya

Reputation: 906

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

Upvotes: 3

Related Questions