dimanche 28 août 2016

Reactjs Redux should we create sub reducer for every object in the state tree?

redux app as far as i have learned, proper way to maintain your state tree is to normalize it, flaten data as far as possible and use combinereducer to create slices of the state tree.

example App that has posts and users

const rootReducer = combineReducers({
  user:userReducer,
  posts:postsReducer,
});
const store = createStore(rootReducer);

given posts array keep all posts init, State.posts can look like

let initialState =   {
    byId:{1:{id:1,title:'post1'}},
    ids:[1],
    meta_data:{unread:1,old:0}
    }

now if we have around 10,000 posts we would end up with state.post.ids.length === 10000 and this is fine,

Question is. since our reducer returns a new state every time it needs to update for example we need to update the meta_data.unread to be equal 0, we will return a new Post object.

return object.assign({},state,{meta_data:{unread:0,old:1}})

which will re-render all Selectors and components that consume any attribute of state.post tree !

which sound like a problem right ?** all we wanted is updating unread counter.. why recalculate all selectors and components of Posts ?

so i had this idea that may be the state.posts should also be composed used combineReducers so that every attr. of posts should have a reducer it self.

splitting postsReducer into multiple

postsMainReducer, ==> deal with adding or removing posts
postMeta_dataReducer, ==> deal with meta_data of posts
singlePostReducer ==> Now this is dynamic !! how can i create such ??

is this correct ?, i'm adding more complexity than needed ?

-->can someone point show us a picture of an already running enterprise app state tree ? so we can learn how from it how to organize state ?

Aucun commentaire:

Enregistrer un commentaire