DEV Community

Vishal Tiwari
Vishal Tiwari

Posted on

Redux toolkit: React Thunk and React Saga.Learn from Vishal Tiwari.

React Thunk and React Saga are middleware libraries for handling side effects in React applications, especially for managing asynchronous operations like API calls. Both are commonly used with Redux but serve slightly different purposes and approaches.


React Thunk

1. Overview:

React Thunk is a middleware that allows you to write action creators that return functions instead of action objects. This is useful for handling asynchronous operations like API requests or complex synchronous logic (like conditional dispatching of actions). The returned function receives dispatch and getState as arguments, allowing you to dispatch other actions or access the current state within the function.

2. Key Concepts:

  • Middleware: Thunk is middleware that extends the store's ability to handle functions (i.e., thunks).
  • Asynchronous actions: With Thunk, you can delay the dispatch of an action or dispatch it conditionally based on a certain state or logic.
  • Simple: Thunk is relatively straightforward, making it easy to use for most use cases.

3. How it Works:

  • Normally, action creators return plain JavaScript objects (actions).
  • With Thunk, an action creator can return a function (the "thunk") that receives dispatch and getState. Inside this function, you can perform asynchronous logic (e.g., fetching data from an API) and then dispatch the real action.

4. Example:

Here's a basic example of how you would use redux-thunk in a React app:

   // Action Creator with Thunk
   export const fetchUser = () => {
     return async (dispatch) => {
       dispatch({ type: 'FETCH_USER_REQUEST' });
       try {
         const response = await fetch('/api/user');
         const data = await response.json();
         dispatch({ type: 'FETCH_USER_SUCCESS', payload: data });
       } catch (error) {
         dispatch({ type: 'FETCH_USER_FAILURE', payload: error });
       }
     };
   };
Enter fullscreen mode Exit fullscreen mode

5. Advantages of Thunk:

  • Simplicity: Thunk is easy to understand and implement.
  • Small footprint: It's lightweight and doesn't require complex configurations.
  • Direct control over dispatching: You have more control over when and how actions are dispatched.

6. Drawbacks:

  • Hard to scale: For complex asynchronous flows, Thunk can get messy, with nested logic and lots of dispatch calls.
  • Less structure: Thunk doesn’t enforce a particular structure for managing side effects, which can lead to inconsistent code if not handled properly.

React Saga

1. Overview:

React Saga is a middleware that allows you to handle side effects in a more organized way using generator functions. Instead of returning functions like Thunk, it uses an "effect" system to manage asynchronous operations and control the flow of your logic. Sagas are long-running background processes that can listen to dispatched actions and perform side effects like API calls, data fetching, and other tasks.

2. Key Concepts:

  • Generator functions: Sagas are implemented using ES6 generator functions (function*), which allow you to write asynchronous code that looks synchronous.
  • Watchers and workers: Sagas are often divided into "watcher" sagas (which listen for dispatched actions) and "worker" sagas (which handle the side effects).
  • Take, put, call: Redux-Saga provides effect creators (take, put, call, etc.) to control when to trigger side effects, dispatch actions, and call APIs.

3. How it Works:

  • With Redux-Saga, you define sagas (long-running background tasks) that are responsible for handling side effects.
  • Sagas are typically written as generator functions and yield effects like call (to invoke functions) and put (to dispatch actions).
  • Sagas can also wait for specific actions with take or listen for any actions with takeEvery or takeLatest.

4. Example:

Here’s a basic example of how redux-saga can be used:

   import { call, put, takeLatest } from 'redux-saga/effects';

   // Worker saga: will be fired on FETCH_USER_REQUEST actions
   function* fetchUser(action) {
     try {
       const response = yield call(fetch, '/api/user');
       const data = yield response.json();
       yield put({ type: 'FETCH_USER_SUCCESS', payload: data });
     } catch (e) {
       yield put({ type: 'FETCH_USER_FAILURE', message: e.message });
     }
   }

   // Watcher saga: spawns a new fetchUser task on each FETCH_USER_REQUEST
   function* mySaga() {
     yield takeLatest('FETCH_USER_REQUEST', fetchUser);
   }

   export default mySaga;
Enter fullscreen mode Exit fullscreen mode

5. Advantages of Redux-Saga:

  • Better for complex side effects: Saga's effect-based approach is more scalable and suited for managing complex asynchronous flows (e.g., dealing with retries, debouncing, or cascading API calls).
  • Testable: Sagas are easy to test since they are built around generator functions.
  • Declarative: The use of effects makes it clearer what side effects will happen, making the flow more predictable.
  • Cancellations and sequences: Saga makes it easy to cancel ongoing tasks or enforce sequence flows of events (like waiting for multiple actions).

6. Drawbacks:

  • Steeper learning curve: Using generator functions and the overall saga pattern can be difficult for beginners to grasp.
  • Overhead: For small applications, it might feel like overkill compared to simpler solutions like Thunk.
  • Verbose: Sagas tend to involve more boilerplate code compared to Thunk.

Comparison: React Thunk vs. React Saga

Aspect React Thunk React Saga
Concept Returns functions in action creators Uses generator functions for side effects
Learning curve Easier to learn and use Higher learning curve due to generators
Asynchronous flow Handles simple async logic Better for complex async workflows
Code structure Less structure, can get messy in large apps Provides a clear, structured approach
Testing Testing can be more challenging Easier to test because of generators
Use cases Simple async logic, API requests Complex flows (e.g., sequences, retries)
Performance Lightweight More powerful, but slightly more overhead

When to Use Which?

  • Use React Thunk if:

    • Your application has relatively simple asynchronous needs, such as basic API requests and dispatching based on conditions.
    • You want a lightweight, easy-to-understand solution without much boilerplate.
  • Use React Saga if:

    • You need to manage more complex asynchronous flows, like retries, action sequencing, race conditions, or multiple tasks that depend on one another.
    • You prefer the declarative approach and want better control over side effects.
    • Your app requires better testability and code maintainability in the long run.

Top comments (1)

Collapse
 
vishal_tiwari_114f21d14e5 profile image
Vishal Tiwari

If you have any doubt related to Mern Stack or AI.Feel free to ask your queries here only.