Thành's Blog

useDebounce

March 26, 2019 • 1 mins

Snippet

import React from 'react'

export const useDebounce = (value: any, delay: number) => {
  const [debouncedValue, setDebounceValue] = React.useState(value)
  React.useEffect(() => {
    const handler = setTimeout(() => setDebounceValue(value), delay)
    return () => clearTimeout(handler)
  }, [value, delay])

  return debouncedValue
}

Usage

import React from 'react'
import { useDebounce } from './hooks/useDebounce'


export const ExampleDebounce = () => {
  const [inputValue, setInputValue] = React.useState('')
  const searchQuery = useDebounce(inputValue, 500)

  const search = async () => {
    // do something with search query
  }

  React.useEffect(() => {
    search()
  }, [searchQuery])

  return (
    <input
      value={inputValue}
      onChange={event => setInputValue(event.target.value)}
    />
  )
}
2018 © Thành
RSS