Blog>
Snippets

Debouncing User Input in Redux-Saga

Illustrate how to implement debouncing in Redux-Saga to handle rapid user input, such as search text input, efficiently by delaying the execution of the associated saga until user input pauses for a specified duration.
import { debounce, put, call } from 'redux-saga/effects';

function* fetchSearchResults(action) {
  // Your API call logic here
  const results = yield call(Api.fetch, action.payload.query);
  yield put({ type: 'SEARCH_RESULTS_RECEIVED', results });
}
This is a saga that performs the API request to fetch search results based on the user's query.
import { takeLatest } from 'redux-saga/effects';

function* watchSearchInput() {
  // Debounce search input actions
  // Waits for 500ms of inactivity on SEARCH_INPUT_CHANGED before triggering
  yield debounce(500, 'SEARCH_INPUT_CHANGED', fetchSearchResults);
}
This saga watches for the SEARCH_INPUT_CHANGED action and debounces it. Only after 500ms of pause in actions will it call the fetchSearchResults saga, minimizing unnecessary API calls during rapid input.