Skip to content

Instantly share code, notes, and snippets.

@dandelionadia
Created October 4, 2019 14:05
Show Gist options
  • Save dandelionadia/f299dcf4cc1036a873b97819c6e411b3 to your computer and use it in GitHub Desktop.
Save dandelionadia/f299dcf4cc1036a873b97819c6e411b3 to your computer and use it in GitHub Desktop.
react functional component debounce
import React, { useState, useRef } from 'react'
import debounce from 'lodash.debounce'
const Search = () => {
// state text which was written in the input
const [value, setValue] = useState('')
// using "useRef" so that React doesn't create
// debounced function on each render (after state update).
const doSearch = useRef(
// using debounce to delay request to backend
debounce(searchQuery => {
// backend request to do search
fetch(`https://back.end?q=${searchQuery}`)
}, 300)
).current
const handleChange = event => {
const nextValue = event.target.value
// update input value
setValue(nextValue)
// do search request
doSearch(nextValue)
}
return (
<input value={value} onChange={handleChange} />
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment