Debouncing and Throttling Events in React JS

When working with user interactions in React, such as keypresses, scrolling, or window resizing, events can trigger frequently, leading to performance issues. In such cases, techniques like debouncing and throttling are useful for controlling how often a function is executed, improving both performance and user experience. In this article, we will explore these two techniques in React, understand how they work, and look at examples of when and how to use them.

What is Debouncing?

Debouncing is a technique used to limit the rate at which a function is invoked. When an event is triggered repeatedly (e.g., a user typing into a search input), the function is not executed until a certain amount of time has passed since the last event. This ensures that the function is executed only once after the user has stopped triggering the event for a predefined period, reducing unnecessary calls to the function.

Example of Debouncing in React

Consider a search input field where you only want to trigger an API call after the user has stopped typing for a certain period. Using debouncing will delay the API call until the user finishes typing.

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

              function SearchComponent() {
                  const [query, setQuery] = useState('');
                  const [debouncedQuery, setDebouncedQuery] = useState(query);

                  // Debounce function to delay the API call
                  useEffect(() => {
                      const timer = setTimeout(() => {
                          setDebouncedQuery(query);
                      }, 1000); // 1-second debounce delay

                      return () => clearTimeout(timer); // Clean up on re-render
                  }, [query]);

                  useEffect(() => {
                      // Example API call triggered when query changes
                      if (debouncedQuery) {
                          console.log('API call with query: ' + debouncedQuery);
                      }
                  }, [debouncedQuery]);

                  return (
                      
setQuery(e.target.value)} placeholder="Search..." />
); } export default SearchComponent;

In this example, when the user types in the search input, the state query is updated. However, the actual API call (simulated by console.log) is made only after the user has stopped typing for 1 second, thanks to the debounce implemented in the useEffect hook.

What is Throttling?

Throttling is another technique to limit the rate at which a function is called. Unlike debouncing, throttling ensures that a function is called at regular intervals, regardless of how often an event is triggered. This is useful in scenarios like scrolling or resizing windows, where you want to perform an action at a fixed interval, instead of executing it continuously as the event is triggered.

Example of Throttling in React

Consider a scenario where you are tracking the scroll position of a page and want to limit how often the scroll event handler is called. Throttling can be used here to execute the scroll handler only once every 200 milliseconds, regardless of how fast the user scrolls.

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

              function ScrollTracker() {
                  const [scrollPosition, setScrollPosition] = useState(0);

                  // Throttle function to limit the frequency of scroll updates
                  useEffect(() => {
                      const handleScroll = () => {
                          setScrollPosition(window.scrollY);
                      };

                      // Throttling the scroll event handler
                      const throttledScroll = () => {
                          let lastScrollTime = 0;
                          return () => {
                              const now = Date.now();
                              if (now - lastScrollTime >= 200) { // 200 ms throttle interval
                                  handleScroll();
                                  lastScrollTime = now;
                              }
                          };
                      };

                      const throttleScroll = throttledScroll();
                      window.addEventListener('scroll', throttleScroll);

                      return () => window.removeEventListener('scroll', throttleScroll);
                  }, []);

                  return (
                      

Scroll Position: {scrollPosition}

); } export default ScrollTracker;

In this example, the throttledScroll function ensures that the handleScroll function is called only once every 200 milliseconds. This prevents the scroll handler from being triggered too frequently, improving performance while still keeping track of the scroll position.

Debouncing vs. Throttling

Both debouncing and throttling are used to optimize performance, but they serve different purposes:

  • Debouncing: Delays the execution of the function until a certain amount of time has passed since the last event. It's ideal for cases where you only want the function to run after the user stops triggering the event (e.g., searching, input validation).
  • Throttling: Ensures that the function is called at regular intervals, even if the event is triggered continuously. It's ideal for events that occur frequently, like scrolling or resizing.

When to Use Debouncing and Throttling

Use debouncing when you want to limit the frequency of a function based on the user finishing their action (e.g., typing in a search bar or validating form input). On the other hand, use throttling when you want to ensure that the function is called at a fixed rate during a continuous event (e.g., tracking scroll or resizing events).

Conclusion

Debouncing and throttling are both powerful techniques that help improve the performance of React applications by limiting the rate at which event handlers are called. Debouncing is useful for actions that occur as a result of user input, where you only want to react once the user has finished their action. Throttling is ideal for continuous events like scrolling or resizing, ensuring that performance remains smooth without overloading the system with too many event triggers.





Advertisement