Issue
With Redux, would it be more logical to keep an extremely large (more than 4000 values) state with a single reducer or to divide the state into multiple parts and keep them in reducers?
Solution
The size of the state shouldn't be the deciding factor, but rather it is the complexity, e.g. the structure, of the state that should be. A single reducer owning a slice of state with 4000 properties or array elements is completely fine, but if the 4000 values form an object with deeply nested properties, well then this makes for a case for splitting the nested properties out into their own sub-state, e.g. reducers, which are then combined together to form the reducer tree, e.g. the state tree.
In other words:
If the state is a flat structure of 4000 related properties/values, then a single reducer is fine.
const initialState = {};
const myState = createSlice({
name: "myState",
initialState,
reducers: {
updateMyState: (state, action) => {
const { key, value } = action.payload;
state[key] = value;
},
},
});
If the state shape is more complex, split the state up so each slice of state is responsible for a single non-nested "chunk" of it.
Example:
const initialState = {};
const foo = createSlice({
name: "foo",
initialState,
reducers: {
updateFoo: (state, action) => {
const { key, value } = action.payload;
state[key] = value;
},
},
});
const initialState = {
someArray: [],
};
const foo = createSlice({
name: "bar",
initialState,
reducers: {
updateBar: (state, action) => {
state.someArray.push(action.payload);
},
},
});
const initialState = {
isBuzz: false,
};
const bizz = createSlice({
name: "bizz",
initialState,
reducers: {
updateBizzBuzz: (state, action) => {
state.isBuzz = action.payload === "buzz";
},
},
});
const foobar = combineReducers({
foo: foo.reducer,
bar: bar.reducer,
});
const rootReducer = combineReducers({
foobar,
buzz: buzz.reducer
});
const store = configureStore({
reducer: rootReducer,
});
You can see here how the reducers form a state tree:
state
+--foobar
| +--foo
| +--bar
| +--someArray
+--buzz
+--isBuzz
The general suggestion or "rule of thumb" is that each state slice/reducer should only be responsible for a "flat" or very shallow group of related values.
Answered By - Drew Reese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.