Open In App

How to debounce or throttle input changes in React?

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Debouncing and throttling are techniques used to limit the frequency of certain actions, particularly useful for handling input changes like those from user interactions.

Debouncing:

  • Imagine you have a text input field where users are typing. Each keystroke triggers some action, like filtering search results. With debouncing, instead of performing the action immediately on every keystroke, you wait a brief moment after the last keystroke before performing the action.
  • You’re typing in the search bar, and as soon as you stop typing (pause for a moment), then the search is triggered. If you start typing again before that moment is up, the timer resets.
  • This prevents the action from being triggered too frequently, especially in situations where rapid changes aren’t necessary, such as autocomplete suggestions where you don’t need to search for every single letter typed.

Throttling:

  • Throttling is similar to debouncing in that it limits the rate at which a function is executed. However, instead of waiting for a pause before executing the function, throttling ensures the function is executed at a regular interval, regardless of how many times it’s triggered.
  • Picture it like this: You’re scrolling through a webpage, and there’s a function that checks your scroll position and does something (like updating an animation or loading more content). With throttling, even if you scroll like crazy, the function will only execute every, say, 100 milliseconds.
  • This prevents performance issues that might arise from excessively frequent function calls, especially in scenarios like scrolling or mouse movement tracking.

Example: Below is an example of debounce and throttle input changes.

  • We use the useState hook to manage the input value (inputValue) and the debounced (debouncedValue) and throttled (throttledValue) versions of the input value.
  • We use the useEffect hook to perform debouncing and throttling. Inside the effect, we set a timer to update the debounced or throttled value after a certain delay when the input value changes.
  • The debounce time is set to 500 milliseconds, and the throttle time is set to 1000 milliseconds in this example.
  • We have an input element controlled by the inputValue state, and its onChange event triggers the handleChange function to update the input value state.
  • Below the input, we display the debounced and throttled values, which get updated after the specified delay when the input value changes.

Javascript




import React, {
    useState,
    useEffect
} from 'react';
 
const InputComponent = () => {
    const [inputValue, setInputValue] = useState('');
    const [debouncedValue, setDebouncedValue] = useState('');
    const [throttledValue, setThrottledValue] = useState('');
 
    useEffect(() => {
        console.log('Input value changed:', inputValue);
 
        const debounceTimer = setTimeout(() => {
            console.log(`Debounce timer expired.
      Updating debounced value:`, inputValue);
            setDebouncedValue(inputValue);
        }, 500); // Debounce time: 500 milliseconds
 
        return () => {
            console.log('Clearing debounce timer');
            clearTimeout(debounceTimer);
        };
    }, [inputValue]);
 
    useEffect(() => {
        console.log('Input value changed:', inputValue);
 
        const throttleTimer = setTimeout(() => {
            console.log(`Throttle timer expired.
            Updating throttled value:`, inputValue);
            setThrottledValue(inputValue);
        }, 1000); // Throttle time: 1000 milliseconds
 
        return () => {
            console.log('Clearing throttle timer');
            clearTimeout(throttleTimer);
        };
    }, [inputValue]);
 
    const handleChange = (event) => {
        console.log('Input value changing:',
            event.target.value);
        setInputValue(event.target.value);
    };
 
    return (
        <div>
            <input type="text"
                value={inputValue} onChange={handleChange}
                placeholder="Type something..." />
            <div>
                <p>Debounced value: {debouncedValue}</p>
                <p>Throttled value: {throttledValue}</p>
            </div>
        </div>
    );
};
 
export default InputComponent;


Output:

gfg43

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads