Search code examples
reactjsreact-hookslodash

debounce lodash how to reset the state so that the function is called after a while


how to make it so that when button clicks stop after a second, the _debounce function displays the inscription button clicks are over? Now it turns out that if you click all the time, then the function works all the time and accumulates

https://codesandbox.io/s/kind-leftpad-hex0ul

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

import _debounce from "lodash/debounce";
import "./styles.css";

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    _debounce(() => console.log("counter increment is widespread"), 1000)();
  }, [count]);

  return (
    <div className="App">
      <p>you clicked {count} </p>
      <button onClick={() => setCount(count + 1)}>Click on me</button>
    </div>
  );
}

Solution

  • You can use useMemo and debounced state

    codesandbox example

    import React, { useState, useEffect, useCallback, useMemo } from "react";
    
    import _debounce from "lodash/debounce";
    import "./styles.css";
    
    export default function App() {
      const [count, setCount] = useState(0);
      const [debouncedCount, setDebouncedCount] = useState(0);
    
      const updateCount = useMemo(() => {
        return _debounce((val) => {
          setCount(val);
        }, 1000);
      }, []);
    
      const update = (value) => {
        updateCount(value);
        setDebouncedCount(value);
      };
    
      return (
        <div className="App">
          <p>you clicked {count} </p>
          <button onClick={() => update(debouncedCount + 1)}>Click on me</button>
        </div>
      );
    }