Logo

dev-resources.site

for different kinds of informations.

Decreasing server load by using debouncing/throttle technique in reactjs

Published at
1/15/2025
Categories
react
webdev
javascript
programming
Author
keshav___dev
Author
12 person written this
keshav___dev
open
Decreasing server load by using debouncing/throttle technique in reactjs

Debouncing and Throttling in React.js

Debouncing and throttling are techniques used to optimize performance by controlling the frequency of function execution in response to frequent events (e.g., typing, scrolling, resizing).


1. What is Debouncing?

Debouncing delays the execution of a function until after a certain amount of time has passed since the last time it was invoked.

Use Case Example:

  • Search input field: Avoid triggering an API call on every keystroke.

Debouncing Example in React

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

const DebouncedSearch = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [debouncedValue, setDebouncedValue] = useState('');

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(searchTerm);
    }, 500); // Delay of 500ms

    return () => {
      clearTimeout(handler); // Cleanup on input change
    };
  }, [searchTerm]);

  useEffect(() => {
    if (debouncedValue) {
      console.log('API Call with:', debouncedValue);
      // Make API call here
    }
  }, [debouncedValue]);

  return (
    <input
      type="text"
      placeholder="Search..."
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
};

export default DebouncedSearch;
Enter fullscreen mode Exit fullscreen mode

2. What is Throttling?

Throttling ensures that a function is executed at most once in a specified time interval, regardless of how many times it is triggered during that interval.

Use Case Example:

  • Scroll event: Limit the frequency of a function triggered during a scroll event to improve performance.

Throttling Example in React

import React, { useEffect } from 'react';

const ThrottledScroll = () => {
  useEffect(() => {
    const handleScroll = throttle(() => {
      console.log('Scroll event fired');
    }, 1000); // Execute at most once every 1000ms

    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return <div style={{ height: '200vh' }}>Scroll the page</div>;
};

// Throttle function implementation
const throttle = (func, limit) => {
  let lastFunc;
  let lastRan;
  return function (...args) {
    const context = this;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(() => {
        if (Date.now() - lastRan >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
};

export default ThrottledScroll;
Enter fullscreen mode Exit fullscreen mode

3. Using Libraries (Optional)

Instead of implementing custom debounce/throttle, you can use popular libraries like:

Lodash

Install:

npm install lodash
Enter fullscreen mode Exit fullscreen mode

Usage:

import { debounce, throttle } from 'lodash';

// Debounce Example
const debouncedFunc = debounce(() => console.log('Debounced!'), 500);

// Throttle Example
const throttledFunc = throttle(() => console.log('Throttled!'), 1000);
Enter fullscreen mode Exit fullscreen mode

React-use

Install:

npm install react-use
Enter fullscreen mode Exit fullscreen mode

Usage:

import { useDebounce, useThrottle } from 'react-use';

const Demo = () => {
  const [value, setValue] = useState('');
  const debouncedValue = useDebounce(value, 500);
  const throttledValue = useThrottle(value, 1000);

  useEffect(() => {
    console.log('Debounced:', debouncedValue);
    console.log('Throttled:', throttledValue);
  }, [debouncedValue, throttledValue]);

  return (
    <input
      value={value}
      onChange={(e) => setValue(e.target.value)}
      placeholder="Type something..."
    />
  );
};

export default Demo;
Enter fullscreen mode Exit fullscreen mode

Key Differences

Feature Debouncing Throttling
Execution Executes once after the user stops firing events for a specified time. Executes at regular intervals during the event.
Use Cases Search input, resizing, form validation. Scroll events, button clicks, API polling.
Performance Reduces the number of function calls. Limits execution to once per interval.

When to Use

  • Debouncing: When you want to delay execution until the user stops an action (e.g., waiting for typing to finish).
  • Throttling: When you want to control the rate of execution (e.g., ensuring smooth scrolling performance).

Both techniques can significantly improve performance and user experience when used appropriately!

programming Article's
30 articles in total
Programming is the process of writing, testing, and maintaining code to create software applications for various purposes and platforms.
Favicon
7 Developer Tools That Will Boost Your Workflow in 2025
Favicon
What ((programming) language) should I learn this year, 2025 ?
Favicon
Lessons from A Philosophy of Software Design
Favicon
🕒 What’s your most productive time of the day?
Favicon
Designing for developers means designing for LLMs too
Favicon
Unique Symbols: How to Use Symbols for Type Safety
Favicon
Filling a 10 Million Image Grid with PHP for Internet History
Favicon
When AI Fails, Good Documentation Saves the Day 🤖📚
Favicon
The Language Server Protocol - Building DBChat (Part 5)
Favicon
Основы изучения Python: Руководство для начинающих
Favicon
GraphQL Transforming API Development
Favicon
Easy Discount Calculation: Tax, Fees & Discount Percentage Explained
Favicon
Example of using Late Static Binding in PHP.
Favicon
Top 5 Python Scripts to Automate Your Daily Tasks: Boost Productivity with Automation
Favicon
How to Resolve the 'Permission Denied' Error in PHP File Handling
Favicon
7 Mistakes Developers Make When Learning a New Framework (and How to Avoid Them)
Favicon
Why Is Everyone Unhappy With JavaScript? | State of Javascript 2024 Survey
Favicon
Python в 2025: стоит ли начинать с нуля? Личный опыт и рекомендации
Favicon
Cómo gestionar tus proyectos de software con Github
Favicon
Decreasing server load by using debouncing/throttle technique in reactjs
Favicon
2429. Minimize XOR
Favicon
➡️💡Guide, Innovate, Succeed: Becoming a Software Development Leader 🚀
Favicon
Debugging Adventure Day 1: What to Do When Your Code Doesn’t Work
Favicon
🚀 New Book Release: "Navigate the Automation Seas" – A Practical Guide to Building Automation Frameworks
Favicon
Булеві типи і вирази
Favicon
Build a Secure Password Generator with Javascript
Favicon
join my project semester simulator
Favicon
Как создать свой VPN и получить доступ ко всему?
Favicon
Revolutionary AI Model Self-Adapts Like Human Brain: Transformer Shows 15% Better Performance in Complex Tasks
Favicon
Flow Networks Breakthrough: New Theory Shows Promise for Machine Learning Structure Discovery

Featured ones: