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>
);
}
CodePudding user response:
If I understood your question correct this code will work.
import React, { useState, useEffect } from "react";
import _debounce from "lodash/debounce";
import "./styles.css";
export default function App() {
const [count, setCount] = useState(0);
const handleCount = _debounce((count) => {
setCount(count)
}, 1000)
return (
<div className="App">
<p>you clicked {count} </p>
<button onClick={() => handleCount(count 1)}>Click on me</button>
</div>
);
}
CodePudding user response:
You can use useMemo
and debounced state
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>
);
}