1. Problem background
import { debounce } from 'lodash'; const [searchKey, setSearchKey] = useState(''); // Anti-shake function const debounceList = debounce(getList, 500);
<Input value={searchKey} onChange={(e) => { setSearchKey(); }} className={`${}`} placeholder="Please enter keywords" />
There is a search box on the page. The searchKey is the responsive data defined by useState. The onChange event calls the setSearchKey method. So as long as the input changes, the component will re-render and regenerate the new anti-shake function debounceList. Eventually, the anti-shake function fails.
2. Solution
Use useRef to define searchKey data, making it non-responsive data, and get and modify the values:
// Search for keywords const searchKey = useRef(''); // Modify dataconst setSearchKey = (val) => { = val; };
<Input onChange={(e) => { setSearchKey(); }} className={`${}`} placeholder="Please enter keywords" />
3. Expand
Regarding the problem of handling anti-shake failure, some people may think of using useCallback to cache debounce anti-shake function, for example, you might write this:
const [searchKey, setSearchKey] = useState(''); const debounceList = useCallback(debounce(getList, 500), []);
Although the anti-shake function takes effect, you cannot get the latest searchKey value; if you want to get the latest searchKey value, you have to add the searchKey to the [ ] later, but this anti-shake is invalid again. Therefore, it can only be solved by using useRef to define non-responsive data.
This is the article about the failure of the debounce anti-shake function in react component. For more related debounce anti-shake content in react component, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!