Implement a cache middleware for Redux

One of the reason I love Redux so much, is the ability of providing alternative UIs while reusing most of the business logic. The thinner your presentation layer is, the easier you can replace it. People usually wonder what UI framework, or UI library should I use, should I use Angular, or React or Vue? I don't have the answer, frankly. There is no winner or looser. But I know that if we do it right, you can easily replace the presentation layer whenever you want, while reusing your business logic.

Ok, this post is not about Redux. If you don't know what Redux is, check our its website Redux.org, and make sure you read this excellent post from Dan Abramov before deciding to go with Redux or not. This post is about creating a cache middleware in Redux. Imagine you have a feature where people can click on a button to fetch data from a server. Then you want to add the cache layer above it, to make sure you don't request the data again if nothing changes. How to do this in a good way? How to add the cache layer without modifying your existing actions and reducers? How to do it so you can enable or disable the cache layer? I hope this post can help you to answer those questions.

To do that, we will create a cache middleware and register it in Redux using applyMiddleware. With this cache middleware, you can enable or disable it without the need of modifying other parts.

Here is the code: Embedded content: https://gist.github.com/tonnguyen/54ceb391c718a1f9e06e55810cbeaac4

The cache middleware checks if the cache is available to return, otherwise, it let the action to be processed by live middleware. Live middleware is just an example, you can modify it to fetch data from the real server. As you can see, nothing need to be changed in the reducer!

Want to try it out? Check out the demo at: https://stackblitz.com/edit/redux-cache-middleware