How to use throttle or debounce with React Hook?

后端 未结 17 1007
甜味超标
甜味超标 2020-11-30 04:27

I\'m trying to use the throttle method from lodash in a functional component, e.g.:

const App = () => {
  const [value, setValue         


        
17条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 05:08

    I do not know whether you use Redux or not -presumably not. However, I had similar problem and solved that with Saga.

    import { put, all, takeLatest } from "redux-saga/effects";
    
    const delay = (ms) => new Promise((res) => setTimeout(res, ms));
    
    function* throttledSort(e) {
      yield delay(400);
      yield put({ type: "SORT", payload: e.payload });
    }
    
    function* watchSort() {
      yield takeLatest("THROTTLED_SORT", throttledSort);
    }
    
    export default function* rootSaga() {
      yield all([watchSort()]);
    }
    

    What it precisely does is throttling dispatch of SORT action. In your component then one should use THROTTLED_SORT and not just SORT

    let throttledSort=(e) => action('THROTTLED_SORT', e.target.cellIndex);
    

    That is not precisely answer to your question but might be useful, anyway (if you think it is too far, please do not undervote)

提交回复
热议问题