Caching GET Requests in NgRx

Erik Slack
ngconf
Published in
6 min readJun 1, 2021

It’s no secret that I’m a big fan of the NgRx Store for Angular. I’m also an avid Firebase user, but the nugget of wisdom I’m about to share with you will be useful with any backend.

Let’s face it, many of the network requests you make to fetch data from a back-end don’t need to happen more than once. Caching can help with that. Caching is predominantly a back-end concern, but it’s also helpful on the front-end side of things if used for the right things.

In this article I’m going to show you how to set up a super simple network cache in your NgRx effects, enabling you to reduce the network traffic in your application down to only what’s absolutely necessary.

What Is Caching?

Caching is when you store the results of an operation away for future use. For the purposes of this article, front-end network caching is the process of storing http responses in memory so that if you need to get the exact same information again you can avoid fetching it from the back-end multiple times.

The Benefits of Front-End Network Caching

There are two primary benefits to caching the responses to your GET requests:

  1. Decrease your network traffic, server requests, and database reads. If you’re charged based on the usage of any of these things, this can save you or your company a non-trivial amount of money. Always try to build discreet systems!
  2. Speed up your users’ experiences because you don’t have to wait for data from another server instead you’re getting the same data from the client’s own machine.

Both of those are pretty sweet rewards for what’s won’t take you very long to implement.

When to Cache Responses

You should cache your responses if you care about lightning-fast responses to your requests. You’ll still have to fetch data once the old-fashioned way though, so manage your expectations accordingly. Another use case is when you need to reduce your data footprint on either your data server or your database. In Firebase and other serverless architectures, reads saved equals money saved.

Save your money so you can afford a new hamster!

When NOT to Cache Responses

You should NOT cache your responses if you are building something that has volatile data or data that changes often. By often I mean within an hour or so. You could still cache your responses in this case, but you’ll have to build a mechanism for expiration into your solution as well. It’s also worth noting that the way you do your pagination might also be a factor. I find caching more effective with standard pagination, but with infinite scroll strategies, you already don’t need to reload data. So is caching necessary? Only you would know for your project.

Another point I should bring up is that some applications don’t care too much about space-complexity and focus on optimizing time complexity. Caching might not be right for an app that cares a lot about every piece of memory it’s using. As you can imagine the cache can grow.

Out-of-the-Box Solutions vs Custom

Why build your own solution when perfectly good ones already exist with more features and documentation than you ever dreamed of maintaining for your custom solution? There are good reasons to go custom. In this case, the custom solution is good enough 90% of the time and it’s not a ton of code. But one caching library I know of is called Cashew. I played with it for a few minutes and decided that it would be easier to just make my own thing since I was using NgRx Effects. In the next section, I’ll tell you how to do that yourself.

Setting Up a Simple Cache in an NgRx Effect

You’re probably thinking by now, “Get to the goods already Erik!” If you were, then keep in mind that the other stuff is for people who need a bit more context and advice. This part is the main course of this meal though!

Step 1: Get Started With NgRx Store and Effects!

Teaching you how to get started with NgRx Store and Effects isn’t the purpose of this article, but here are some links to help you learn those if you still need to:

Before you move to the next step, you should have a fully-functioning flow of NgRx store and effects. Verify you can get data and display it in your view. Once that’s done move on ahead!

Even when using high-powered tools like NgRx you can still make cool improvements like caching!

Step 2: You’ll Need a Map

First, let’s make a simple map and a variable to hold the currentId we’ll be working with.

Step 3: Update Your Effect to Store Responses

I’m going to move forward with the step of saving the response data to the cache. I don’t necessarily have to save the whole response, I could also just save the part of it that I care about. Consider what works best for your needs.

Step 4: Update Your Effect to Check the Cache First

Finally, we need to make the effect check to see if the serialized action exists as a key in the map before we call the backend for more data.

That’s it! Now if you dispatch the same action to get data twice — or a thousand times — it’s only going to get the data once for as long as your session remains open.

A Note on Persistent Caching

I didn’t cover in this article how to set up expiration or persist your cache. I’ll write a future article on this subject. Feel free to write a comment if you want this follow-up article and it may serve to prod me into writing it faster.

Conclusion

Now every time after the first your user clicks to load something, it won’t load it again, but your NgRx state flow remains pure. You don’t have to put that cognitive burden on yourself and your colleagues to remember when to dispatch the action or not. Your app will always do it the same way every time!

Just a few easy steps and you’re done. Until the next level that is…

I’ve found this technique extremely helpful for UIs that include pagination or detailed-view-screens. For example, you have a list of users and you want to see the details about a specific user. It might take a second to load it the first time, but after that it’s instantaneous. Go you!

Now get out there and build something awesome. Then come tell me about it on Twitter at @erik_slack!

Now that you’ve read this article and learned a thing or two (or ten!), let’s kick things up another notch!
Take your skills to a whole new level by joining us in person for the world’s first MAJOR Angular conference in over 2 years! Not only will You be hearing from some of the industry’s foremost experts in Angular (including the Angular team themselves!), but you’ll also get access to:

  • Expert panels and Q&A sessions with the speakers
  • A friendly Hallway Track where you can network with 1,500 of your fellow Angular developers, sponsors, and speakers alike.
  • Hands-on workshops
  • Games, prizes, live entertainment, and be able to engage with them and a party you’ll never forget

We’ll see you there this August 29th-Sept 2nd, 2022. Online-only tickets are available as well.
https://2022.ng-conf.org/

--

--

Erik Slack
ngconf
Editor for

Husband | Dad | Dev | He/Him (cis) GDE in Angular | SE Technical Lead at Cisco | #BlackLivesMatter