Open In App

What is the difference between synchronous and asynchronous action creators?

In web development, Redux has become very popular for managing application state. Action creators play an important role in Redux, which helps the dispatching of actions to update the state.

In this article, we will understand the difference between synchronous and asynchronous action creators.



Synchronous Action Creators:

Synchronous action creators dispatch actions immediately after they are called. These actions typically represent simple state changes that do not require any external data fetching or asynchronous operations.



Syntax:

const incrementCounter = () => ({
type: 'INCREMENT_COUNTER',
});

Features of Synchronous Action Creators:

Example: In this sample code there is a flow of synchronous action creator to understand.




// Redux setup
import { createStore } from 'redux';
 
// Initial state
const initialState = {
    counter: 0
};
 
// Reducer
const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREMENT_COUNTER':
            return {
                ...state,
                counter: state.counter + 1
            };
        default:
            return state;
    }
};
 
// Create Redux store
const store = createStore(reducer);
 
// Synchronous action creator
const incrementCounter = () => ({
    type: 'INCREMENT_COUNTER'
});
 
// Dispatch the action
store.dispatch(incrementCounter());
 
// Check the updated state
console.log(store.getState()); // Output: { counter: 1 }

Asynchronous Action Creators:

Asynchronous action creators dispatch actions asynchronously, which involves external data fetching or complex operations that require time to complete.

Syntax:

const fetchData = () => {
return async (dispatch) => {
const data = await fetchDataFromAPI();
dispatch({ type: 'FETCH_DATA', payload: data });
};
};

Features of Asynchronous Action Creators:

Example: In this sample code there is a flow of asynchronous action creator to understand.




// Redux setup
 
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
 
// Initial state
const initialState = {
    data: null,
    loading: false
};
 
// Reducer
const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'FETCH_DATA_REQUEST':
            return {
                ...state,
                loading: true
            };
        case 'FETCH_DATA_SUCCESS':
            return {
                ...state,
                loading: false,
                data: action.payload
            };
        default:
            return state;
    }
};
 
// Create Redux store with thunk middleware
const store = createStore(reducer, applyMiddleware(thunk));
 
// Asynchronous action creator
const fetchData = () => {
    return async (dispatch) => {
        dispatch({ type: 'FETCH_DATA_REQUEST' });
 
        try {
            // Simulating API call
            const response = await fetch('https://api.example.com/data');
            const data = await response.json();
 
            dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data });
        } catch (error) {
            // Handle error
            console.error('Error fetching data:', error);
        }
    };
};
 
// Dispatch the asynchronous action
store.dispatch(fetchData());
 
// Check the initial state
console.log(store.getState()); // Output: { data: null, loading: true }

Differences Between Synchronous and Asynchronous Action Creators:

Feature

Synchronous Action Creators

Asynchronous Action Creators

Dispatch Mechanism

Immediate

Asynchronous

Dependencies

No external dependencies

May involve external data fetching or asynchronous operations

Flow Control

Follows a predictable flow

Asynchronous, non-blocking execution

Complexity

Suitable for simple state changes

Ideal for complex state updates involving asynchronous operations

Middleware Integration

Not typically used

Often used with middleware like Redux Thunk or Redux Saga

Conclusion:

Synchronous action creators dispatch actions immediately when invoked, that makes them suitable for simple state changes without external dependencies. On the other hand, asynchronous action creators dispatch actions asynchronously and involves external data fetching or complex computations.


Article Tags :