Sobes.tech
Middle+

const LiveSearch = () => { const [inputValue, setInputValue] = useState('') const onInputChange = (e) => { setInputValue(e.target.value) search(e.target.value) } return ( <div> <input value={inputValue} onChange={onInputChange} type="text" /> </div> ) } <span> Searching for: <LiveSearch /> </span>

sobes.tech AI

Answer from AI

In this LiveSearch component, the search function is called with the current input value every time a character is entered. This can lead to excessive requests, especially if search is a server request.

To optimize, debounce is usually used — delaying the function call until the user stops typing for a certain period. This reduces the number of search calls and improves performance.

An example using debounce with lodash:

import React, { useState, useCallback } from 'react'
import debounce from 'lodash.debounce'

const LiveSearch = () => {
  const [inputValue, setInputValue] = useState('')

  // Wrap search in debounce with a 300 ms delay
  const debouncedSearch = useCallback(
    debounce((query) => {
      search(query)
    }, 300),
    []
  )

  const onInputChange = (e) => {
    const value = e.target.value
    setInputValue(value)
    debouncedSearch(value)
  }

  return (
    <div>
      <input value={inputValue} onChange={onInputChange} type="text" />
    </div>
  )
}

Thus, search is called not on every input, but only after 300 ms from the last character.

It is also important to clear the debounce on component unmount to prevent memory leaks.