ReactJS

What is Debouncing, and Why do I need it?


Consider a search bar that calls the API for every key you type. If you are a fast typist, you are calling the API much more frequently than you need to, which might slow down your application and hurt performance.

And that is where debouncing comes in. It allows you to wait for the user to stop typing before making an API call. It's essentially just debouncing the action, or rather slowing down the action itself so that you do not spam the server uselessly.

What is debouncing in React? and How Does it Work?

Virtualization keeps most of the items in a virtual state. They are not ever actually appended to the DOM until they are needed, rather than rendering all the items at once.

Virtualization happens to only cause those items, falling into the visible part of the container to be rendered and allows other unreferenced in DOM.

The library captures scroll events as the user scrolls and determines which items should appear based on where the user scrolled.

On-The-Fly Rendering: When the user scrolls down, items now in view are quickly added to it; those that are no longer in view are removed. Thus the number of rendering is kept low and scrolling is smooth and very efficient.

1. Using lodash.debounce

  First, install the lodash.debounce package using this command npm install lodash.debounce

Now we can use it in our code like this :    

console.log('API request with:', value); // Write your code import React from 'react';import debounce from 'lodash.debounce';const DebounceInput = () => { const [searchValue, setSearchValue] = React.useState(''); // The debounced function const debouncedSearch = React.useCallback(   debounce((value) => {  console.log('API request with:', value); // Write your code }, 500), // It is customizable according to our needs   [] ); const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {   const { value } = e.target;   setSearchValue(value);   debouncedSearch(value); }; return (   <div>     <input       type="text"       value={searchValue}       onChange={handleChange}       placeholder="Search..."     />   </div> );};export default DebounceInput;

2. Debouncing with Custom Hook

  • It takes an argument value, then waits for a certain amount of milliseconds in this case, 500.
  • In other words, the debounced value is updated only when the user stops typing for that given delay.
  • The actual API request or side effect occurs only when the debounced value changes, which ensures minimum network calls or unnecessary renders.
import { useState, useEffect } from "react";export function useDebounce<T>(value: T, delay: number): T { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => {   // Set a timeout to update the debounced value after the specified delay   const handler = setTimeout(() => {     setDebouncedValue(value);   }, delay);   // Clear the timeout if the value changes before the delay is over   return () => {     clearTimeout(handler);   }; }, [value, delay]); return debouncedValue;}

 

Use this useDebounce hook in Other Component

 

import React, { useState } from 'react';import useDebounce from './useDebounce'; // Enter your path hereconst DebouncedSearch = () => { const [searchValue, setSearchValue] = useState(''); const debouncedSearchValue = useDebounce(searchValue, 500); // API call or any action happens when debouncedSearchValue updates React.useEffect(() => {   if (debouncedSearchValue) {     console.log('Performing API request with search term:', debouncedSearchValue);     // Add your API call logic here   } }, [debouncedSearchValue]); const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {   setSearchValue(e.target.value); }; return (   <div>     <input       type="text"       value={searchValue}       onChange={handleChange}       placeholder="Type to search..."     />   </div> );};export default DebouncedSearch;

 

A Dedicated Hook for Debouncing Advantages Applying

  • Reusability: Now, with this custom hook, you can reuse it wherever you need in your application-whether it is for search inputs form fields or any user action that needs debouncing.
  • Clean Code: The logical representation is abstracted away, so your components are easy to read and maintain.
  • Flexibility: This debounce delay is easy to vary to suit different conditions.

Why not just Use Lodash?

While Lodash is pretty handy for utility functions like this debounce, a custom hook gives you control, and you keep your dependencies small. For relatively small applications or if you're not already using Lodash, it's usually better to write a hook yourself.

Conclusion

In the End Debouncing, actually, is a pretty simple technique yet very powerful for making React applications speedier. You write custom hooks, keep your code base clean, and reuse the logic between different components. So next time you work with a search bar, or maybe any other field for that matter, consider using debouncing in order to make your application better and faster!

 

Ready to transform your business with our technology solutions?   Contact Us today to Leverage Our ReactJS Expertise.

0

React

Related Center Of Excellence