How to throttle input in React

Throttling input in React limits function execution frequency during continuous user interactions, ensuring consistent performance while maintaining regular updates. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented input throttling in real-time dashboards, live data feeds, and interactive visualizations. From my expertise, the most reliable approach is using useRef to track execution timing and useState to manage throttled values with controlled update intervals. This technique prevents performance degradation during rapid input while providing regular feedback for smooth user experiences.

Use useRef to track timing and controlled state updates to limit input processing frequency while maintaining regular updates.

import { useState, useRef, useCallback } from 'react'

function LiveSearchComponent() {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState([])
  const lastExecuted = useRef(0)
  const timeoutRef = useRef(null)

  const throttledSearch = useCallback((searchTerm) => {
    const now = Date.now()
    const timeSinceLastExecution = now - lastExecuted.current

    const executeSearch = () => {
      fetchSearchResults(searchTerm).then(setResults)
      lastExecuted.current = Date.now()
    }

    if (timeSinceLastExecution >= 300) {
      executeSearch()
    } else {
      clearTimeout(timeoutRef.current)
      timeoutRef.current = setTimeout(executeSearch, 300 - timeSinceLastExecution)
    }
  }, [])

  const handleInputChange = (e) => {
    const value = e.target.value
    setQuery(value)
    throttledSearch(value)
  }

  return (
    <input
      value={query}
      onChange={handleInputChange}
      placeholder='Live search...'
    />
  )
}

Here lastExecuted.current tracks when the function last ran, and the throttle logic ensures execution at most every 300ms. If enough time has passed, the function executes immediately. Otherwise, it schedules execution for the remaining time. This provides regular updates during continuous typing while preventing excessive API calls. The useCallback optimizes re-renders.

Best Practice Note:

This is the same approach we use in CoreUI React components for real-time data updates, progress tracking, and live analytics where regular updates are essential during continuous user interaction. Use throttling when you need regular updates during activity, and debouncing when you only need the final result after activity stops.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author