Async Actions in React/React Native Redux

Muesingb
2 min readMay 10, 2020

--

Redux is a state management JavaScript library that can be extremely useful in React and React Native applications. In an application, keeping track of where state and props live and are passed to can quickly get confusing as your application grows. Redux helps simplify this process by storing the application’s state globally in a central store that is then manipulated by components through dispatching actions that get passed to a reducer. The reducer takes an action and updates the central store (application’s state) synchronously. This works great until you need to perform asynchronous actions, such as network requests. In this case, the common way to dispatch asynchronous actions is by using Redux Thunk middleware, which works by having the action creators return a function instead of an action object.

Setup

The setup is relatively simple:

npm install redux-thunk

Then add Thunk to your store file. It should look something like this (uses Redux’s applyMiddleware()):

Actions Examples

Normal Action — returns action object

This action sets the current user to the user given. Notice it returns an object.

Asynch Action — returns function

This action fetches a user’s information given a user id. Notice it returns a function and once the fetch is complete, dispatches a regular action object.

Like the above example, once the asynchronous function is called, you can return to the normal flow of synchronous actions (dispatching the object to a reducer) or can dispatch another action (or actions).

This action creates a new userEvent and the current user attends the event. Notice it is dispatching other actions.

Further Reading

--

--