Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux: drop part of state as unmounting component?

Tags:

reactjs

redux

i'm currently writing an app with react, redux and react-router.

Many of the route (or subroute) of the app, fill the state of the redux store with eventually own reducers that are combined.

but often, the part of the state that is manage by the routed component is specific to this component, and "can be dropped" after the component is unmounted.

i fear that as the user browse different screen, he will fill the state with unused data and bloat the whole app. so i'm thinking about a way to drop part of the state that are unused.

let's take i.e. a CRUD app for multiple distinct entities (Questions, Posts, Images, ....). While i'm listing the Questions it might not be necessary to have Posts in the state, and vice-versa. Should i drop the Posts list while transitioning to the Question list ?

is this a bad practice? is there a good way to do this ? what to you think?

like image 906
eMerzh Avatar asked Apr 12 '16 20:04

eMerzh


2 Answers

Unless you’re dealing with tens of thousands of records, it’s probably not worth the effort and will complicate your code. Are you sure this is a real problem for your app? Keeping the old state is actually handy, e.g. for instant “Back” button.

If you feel strongly about it you can indeed dispatch a cleanup action when unmounting certain components, or on a route change. However I think that in the vast majority of apps this would be unnecessary, and keeping a cache might be preferable as long as you remember to check for any new items after mounting.

like image 95
Dan Abramov Avatar answered Oct 04 '22 02:10

Dan Abramov


If your data was loaded in the detail component (not master), I think it's OK to restore the state.

Because the state of detail component won't actually be 'cached', besides, data will be downloaded again even you are switching back to show the same resource. And if you're going to show a different resource, the residual state of last visited resource remains until data of current resource is downloaded, and that will be wired to the users.

One of the approach is to define an action/reducer to restore the state when the detail component is going to unmount.

Another way is to restore the state when route changes:

import { LOCATION_CHANGE } from 'react-router-redux'
import * as types from 'constants/ActionTypes'

const initialState = {}

export default function show(state = initialState, action) {

  switch (action.type) {

    case types.LOGOUT:
    case LOCATION_CHANGE:
      return initialState

    case types.SHOW_SUCCESS:
      return action.payload

    default:
      return state
  }
}
like image 33
Mingdong Luo Avatar answered Oct 04 '22 03:10

Mingdong Luo