最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Debounce in ReactJS - Stack Overflow

programmeradmin11浏览0评论

I am trying to implement debounce in my search input in React. The below code is causing the delay but its firing the same number of times.

Example - If I type abcd in less than 2 seconds(delay) my debounced value should be abcd instead I am getting console with all values-

Debounced: a 
Debounced: ab 
Debounced: abc 
Debounced: abcd 

What I am assuming, if I type abcd then it should make a single call instead of 4 in this case.

Code -

import { useState } from 'react';

function debounce(cb, delay) {
  let timeoutId;
  return function (...args) {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(() => {
      cb(...args);
    }, delay);
  };
}

export default function App() {
  const [searchVal, setSearchVal] = useState('');
  const [debounceVal, setDebounceVal] = useState('');

  const debouncedChange = debounce((inputValue) => {
    console.log('Debounced:', inputValue);
    setDebounceVal(inputValue);
  }, 2000);

  const handleChange = (e) => {
    const inputValue = e.target.value;
    setSearchVal(inputValue);
    debouncedChange(inputValue);
  };

  return (
    <div className="App">
      <h1>Debounce</h1>

      <div className="container">
        <div className="search-input">
          <input type="text" value={searchVal} onChange={handleChange} />
        </div>

        <div className="search-data">{debounceVal}</div>
      </div>
    </div>
  );
}

Let me know if I am doing something wrong here with the code or my understanding around debounce.

I am trying to implement debounce in my search input in React. The below code is causing the delay but its firing the same number of times.

Example - If I type abcd in less than 2 seconds(delay) my debounced value should be abcd instead I am getting console with all values-

Debounced: a 
Debounced: ab 
Debounced: abc 
Debounced: abcd 

What I am assuming, if I type abcd then it should make a single call instead of 4 in this case.

Code -

import { useState } from 'react';

function debounce(cb, delay) {
  let timeoutId;
  return function (...args) {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(() => {
      cb(...args);
    }, delay);
  };
}

export default function App() {
  const [searchVal, setSearchVal] = useState('');
  const [debounceVal, setDebounceVal] = useState('');

  const debouncedChange = debounce((inputValue) => {
    console.log('Debounced:', inputValue);
    setDebounceVal(inputValue);
  }, 2000);

  const handleChange = (e) => {
    const inputValue = e.target.value;
    setSearchVal(inputValue);
    debouncedChange(inputValue);
  };

  return (
    <div className="App">
      <h1>Debounce</h1>

      <div className="container">
        <div className="search-input">
          <input type="text" value={searchVal} onChange={handleChange} />
        </div>

        <div className="search-data">{debounceVal}</div>
      </div>
    </div>
  );
}

Let me know if I am doing something wrong here with the code or my understanding around debounce.

Share Improve this question asked Sep 17, 2023 at 22:55 NeshNesh 2,5419 gold badges40 silver badges56 bronze badges 1
  • Try wrapping your debounced function in useCallback, that might work – Chris Li Commented Sep 17, 2023 at 23:33
Add a comment  | 

3 Answers 3

Reset to default 11

I would recommend using useEffect hook to listen to any changes and do a clean-up as well. Here's a working DEMO

function useDebounce(cb, delay) {
  const [debounceValue, setDebounceValue] = useState(cb);
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebounceValue(cb);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [cb, delay]);
  return debounceValue;
}

I just worked through this with someone else. The code in question "can" work. The problem is the scope of the let timeout;. Consoling when the function is executed shows it is always undefined in the code you provided.

Try this.

let timeoutId;

function debounce(cb, delay) {
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      cb(...args);
    }, delay);
  };
}

The issue is that every time the App component is re-rendered, the debounce function is recreated, and thus timeoutId has lost its previous scope. That's why, in your example, clearTimeout is never executed, as every change in the input field sets state which causes the App to re-render.

You could use a custom hook that's almost identical to your original function, but leverages the ability of a ref to retain the value of .current between renders:

import { useRef } from "react";

function useDebounce (cb, delay) {
  const timeoutId = useRef();
  
  return function (...args) {
    if (timeoutId.current) { // This check is not strictly necessary
      clearTimeout(timeoutId.current);
    }
    timeoutId.current = setTimeout(
      () => cb(...args), delay
    )
  }
}

Then your debounced function should be the return value of calling the useDebounced hook inside the App component:

const debouncedChange = useDebounce((inputValue) => {
    console.log('Debounced:', inputValue);
    setDebounceVal(inputValue);
  }, 2000);

发布评论

评论列表(0)

  1. 暂无评论