Debounce
Debouncing is a technique used to improve performance by delaying the execution of a function until after a specified time has passed since the last invocation. This is especially useful for optimizing search inputs, API calls, and event listeners.
See it in Action 👇🏻
Without Debounce, API will be called on every input
Bad
With Debounce, API will be called after x-ms of no input
Good
Follow below steps 👇🏻
useDebounce Hook
Add the useDebounce hook to your custom hooks collection by copying the code below.
1import { useState, useEffect } from "react";23function useDebounce<T>(value: T, delay: number): T {4const [debouncedValue, setDebouncedValue] = useState(value);56useEffect(() => {7const handler = setTimeout(() => {8setDebouncedValue(value);9}, delay);1011return () => {12clearTimeout(handler);13};14}, [value, delay]);1516return debouncedValue;17}1819export default useDebounce;
Usage
1import { useState } from "react";2import useDebounce from "./useDebounce";34function SearchComponent() {5const [searchTerm, setSearchTerm] = useState("");6const debouncedSearch = useDebounce(searchTerm, 500);78useEffect(() => {9// ? Debounced search value will change after 500ms of no input,10// ? and that's when the API call will be made11// ? This prevents API calls on every keystroke12if (debouncedSearch) {13console.log("API Call with: ", debouncedSearch);14}15}, [debouncedSearch]);1617return (18<input19type="text"20placeholder="Search..."21value={searchTerm}22onChange={(e) => setSearchTerm(e.target.value)}23/>24);25}2627export default SearchComponent;
⭐️ Got a question or feedback?
Feel free to reach out!