A very common pattern in Redux is to use things called a Thunks, which are a way of wrapping up certain logic of a subroutine in a single function. In the context of Redux, this means taking a set of asynchronous or state-dependent action dispatches and wrapping them in a single action creator.

Let’s see an example: we’re going to have a button that dispatches an action and creates a new notification to show in a different part of the UI.

In the above, we’re using props.dispatch and creating the action objects directly, rather than action creators which are bound by react-redux. We could of course use those as well:

These are effectively the same, it just changes some of the boilerplate to allow you to use actions via “creator” functions instead of directly dispatching objects, which helps separate concerns and reduce code duplication.

Now, you may look at Example2.js above, and it may look a little different to your application code: Here I’m doing everything in one file, but in a real-world application, you’d likely separate your components and action creators out. For the context of this article, the separation of files doesn’t matter.

The example above is virtually the exact same one as linked in the redux-thunk documentation. If we were to do the above using redux-thunk, then it’d look something like this:

Just as before, show and hide are action creators: they encapsulate the logic of showing or hiding a notification, returning an object that describes the action we’re about to perform.

Then we have showTimed which is different; Rather than returning an object, it returns a function, which seems strange, let me explain:

This function doesn’t actually reach your reducers. Instead using some logic in between the dispatch in your component and receiving the action in your reducers, there’s some logic which is called. This is known as as Middleware.