DEV Community

xertifiedloaded
xertifiedloaded

Posted on

Debounce In React

A function can be made to wait to execute until a certain amount of time has elapsed since it was last called by using a method known as debouncing. In instances in which we wish to avoid generating repetitive or unnecessary function calls that could be costly or lengthy, this can be advantageous.
Consider a search box where the user can type and receive ideas. Every keystroke that calls a function to retrieve suggestions could result in an excessive number of requests being sent to the server, slowing down the program and wasting resources. Alternatively, we may use debouncing to delay the request until after the user has paused typing for some time.
Debouncing prevents extra activations or slow functions from triggering


import { useRoutes } from 'react-router-dom';
import Debounce from './Debounce';
import Layout from './Layout';

function App() {
  return useRoutes([
    {
      path: "/",
      element: <Layout />,
      children: [{
        element: <Debounce />,
        path: "/"
      }]
    }
  ]
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode
import React from 'react'
import { Outlet } from 'react-router-dom'

export default function Layout() {
    return (
        <Outlet />
    )
}

Enter fullscreen mode Exit fullscreen mode
import React, { useState } from 'react';
import styles from './debounce.module.css'
export default function Debounce() {
    const [search, setSearchTerm] = useState('');

    const debounceSearch = (value) => {

        clearTimeout(debounceSearch.timeoutId);
        debounceSearch.timeoutId = setTimeout(() => {
            console.log('Searching for:', value);
        }, 300);
    };

    const handleChange = (event) => {
        const { value } = event.target;
        setSearchTerm(value);
        debounceSearch(value);
    };
    return (
        <>
            <section className={styles.main}>
                <input
                    type="text"
                    placeholder="Search..."
                    value={search}
                    onChange={handleChange}
                />
                <div>
                    Searching for {search}
                </div>
            </section>
        </>

    );
};

// export default Debounce;


Enter fullscreen mode Exit fullscreen mode

Top comments (0)