Skip to content

Instantly share code, notes, and snippets.

@mvalipour
Created November 28, 2016 12:48
Show Gist options
  • Save mvalipour/c6a9dcc4b4a935123bfcfbc02a58735b to your computer and use it in GitHub Desktop.
Save mvalipour/c6a9dcc4b4a935123bfcfbc02a58735b to your computer and use it in GitHub Desktop.
Redux: Use store for state not cache

In Redux: use store for state not cache

Background

In Redux, you should not use Store as cache, but rather for things that need to be truly retained, across the application.

For example, when you have a screen to display holidays, and another screen to display details of a holiday:

there is a tendency to keep the list of holidays in the central store, so that when we go "back" from details screen, our list is available immediately (without need to wait for an api call).

Note that in this scenario the central store is used as a cache mechanism rather than a state sharing mechanism (which in this case is not needed).

Problems of doing this:

  • It unncessarily pollutes the central state for what it's not supposed to be
  • can cause memory leak if the things you store are heavy and/or you have tens of screens with this situation

When is it a good idea to use store?

Note there are still scenarios that you may want to keep something like list of holidays in the store. most notably for re-hydrating the state when you have server-rendering.

If that is the case, stop ready and keep storing your items in the store.

But when it comes to these things, in most scenarios, our pages are behind a login screen, so search engines will not be hitting those lists, hence, we don't worry about re-hydration.

What to do instead?

For caching purposes use a caching library ((like this one)[https://www.npmjs.com/package/node-cache]). Caching libraries are good at:

  • Keeping track of how much memory they use
  • Invalidate unused stuff through mechanisms like LRU

-- TODO: more sample code to be included

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment