How do you clean up Redux' state?

Thomas Luzat picture Thomas Luzat · Apr 25, 2016 · Viewed 7.5k times · Source

As a Redux beginner, given (the idea of) a somewhat larger application I imagine a root reducer similar to:

const rootReducer = combineReducers({ accounting, crm, sales })

Application state in this case would contain accounting, crm, and sales even if the user is only using one part of the application. This may be advantageous, for example as a cache when switching back and forth between accounting and CRM, but you probably do not want to retain all data of all views that have ever been opened, that is the complete possible state tree without any pruning, within the application forever or even initializing the whole tree to its initial state on load.

Are there idioms, patterns or libraries which solve this or am I missing something?

As a partial solution which solves retaining all the data I imagine something like resetting parts of the state to their initial state when navigating away from certain parts of the application given some declarative rules such as:

  • set accounting = {} (indirectly, through an action such as ACCOUNTING_LEAVING) when <Accounting/> receives componentWillUnmount
  • delete/set crm.mail = {} when <MailEditor/> receives componentWillUnmount

I have not seen examples which clean up the state in any way. Many "list + detail view" examples store state like { list: [...], detail: {...} }, but when switching to the detail view the list is neither emptied, nor nulled, nor deleted. This is nice when I might return to the list view a couple of moments later, but not when using an application 9 to 5 without ever releasing data.

Answer

markerikson picture markerikson · Apr 25, 2016

A few related thoughts:

  • Unless you're expecting dozens or hundreds of megabytes of data to be cached in your store, you're probably worrying about this too soon. Write your app, benchmark, and then optimize.
  • Dispatching actions to clear out portions of the store is entirely valid and reasonable.
  • My Redux addons ecosystem catalog may have some libraries listed that would be useful. In particular, the Component State and Reducer pages point to some libraries that do things like dynamically adding and removing reducers from your store, and resetting state.
  • You may also be interested in my collection of high-quality React and Redux tutorials.

Overall, how you organize your state, when you update it, and what you update it with is up to you. Redux simply provides a pattern and rules for the process of doing the updates.