Redux Fundamentals, Part 3: State, Actions, and Reducers
- Redux apps use plain JS objects, arrays, and primitives as the state values
- The root state value should be a plain JS object
- The state should contain the smallest amount of data needed to make the app work
- Classes, Promises, functions, and other non-plain values should not go in the Redux state
- Reducers must not create random values like
Math.random()orDate.now() - It’s okay to have other state values that are not in the Redux store (like local component state) side-by side with Redux
- Actions are plain objects with a
typefield that describe what happened- The
typefield should be a readable string, and is usually written as'feature/eventName' - Actions may contain other values, which are typically stored in the
action.payloadfield - Actions should have the smallest amount of data needed to describe what happened
- The
- Reducers are functions that look like
(state, action) => newState- Reducers must always follow special rules:
- Only calculate the new state based on the
stateandactionarguments - Never mutate the existing
state– always return a copy - No “side effects” like AJAX calls or async logic
- Only calculate the new state based on the
- Reducers must always follow special rules:
- Reducers should be split up to make them easier to read
- Reducers are usually split based on top-level state keys or “slices” of state
- Reducers are usually written in “slice” files, organized into “feature” folders
- Reducers can be combined together with the Redux
combineReducersfunction - The key names given to
combineReducersdefine the top-level state object keys
References
https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers