lodash debounce in React functional component not working

前端 未结 3 1796
日久生厌
日久生厌 2021-02-01 04:03

I have a functional component built around the React Table component that uses the Apollo GraphQL client for server-side pagination and searching. I am trying to implement debou

3条回答
  •  生来不讨喜
    2021-02-01 04:30

    debounceLoadData will be a new function for every render. You can use the useCallback hook to make sure that the same function is being persisted between renders and it will work as expected.

    useCallback(debounce(loadData, 1000), []);
    

    const { useState, useCallback } = React;
    const { debounce } = _;
    
    function App() {
      const [filter, setFilter] = useState("");
      const debounceLoadData = useCallback(debounce(console.log, 1000), []);
    
      function handleFilterChange(event) {
        const { value } = event.target;
    
        setFilter(value);
        debounceLoadData(value);
      }
    
      return ;
    }
    
    ReactDOM.render(, document.getElementById("root"));
    
    
    
    
    

提交回复
热议问题