DEV Community

ATUL KUMAR SINGH
ATUL KUMAR SINGH

Posted on

πŸš€ Frontend Tip of the Day: Debouncing Input Handlers for Better Performance πŸš€

When dealing with real-time user input, like search fields, triggering actions on every keystroke can cause performance issues. Debouncing helps by delaying execution until the user stops typing.

πŸ›  Let's Build a Simple Debounce Function:

import React, { useState, useEffect } from 'react';

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

const SearchBar = () => {
  const [query, setQuery] = useState('');

  const handleSearch = (q) => {
    console.log('Searching for:', q);
    // Perform search action here
  };

  const debouncedSearch = debounce(handleSearch, 500);

  useEffect(() => {
    if (query) {
      debouncedSearch(query);
    }
  }, [query]);

  return (
    <input
      type="text"
      placeholder="Search..."
      value={query}
      onChange={(e) => setQuery(e.target.value)}
    />
  );
};
Enter fullscreen mode Exit fullscreen mode

⚑ How it Works:

  • The debounce function accepts a fn (function) and a delay (in milliseconds).
  • It clears any existing timers and sets a new one to trigger the function after the specified delay.
  • In this example, debouncedSearch triggers only after the user stops typing for 500 milliseconds.

πŸ’‘ Why it Matters:
It’s a lightweight solution that improves performance, especially in apps with real-time inputs like search fields.

Happy coding! πŸ”₯

Top comments (0)