Redux Toolkit (RTK) is the "official, opinionated, batteries-included toolset for efficient Redux development".
RTK resolves many of the arguments against Redux related to boilerplate and unnecessary code.
Redux Flow
![Screen Shot 2022-05-05 at 8.19.25 AM](/Users/dev/Library/Application Support/typora-user-images/Screen Shot 2022-05-05 at 8.19.25 AM.png)
The Redux Flow is made up of 3 main components:
Actions –– JS objects with a required type property (among others)
type is simply a string that describes the action (what happened to the state) (ie. ADD_TODO).
They aren't responsible for changing state.
An action is dispatched via the store.dispatch(action) method
// action to add a todo item{ type:'ADD_TODO', text:'This is a new todo'} //action that pass a login payload { type:'LOGIN', payload: { username:'foo', password:'bar' }}
Reducers –– pure functions that handle updating the state
performs the operations on it as instructed by the action
responsible for changing the value of the state
SWITCH-CASE for the action's type
// takes in the current state and action// updates the value based on the action's typefunctioncounterReducer(state = { value:0 }, action) {switch (action.type) {case'INCREASE':return { value:state.value +1 }case'DECREASE':return { value:state.value -1 }default:return state }}
Store –– where all the states are managed.
Finally, the state will be updated in the Store
The components must be subscribed to the Store to listen for state updates to render the states correctly in the UI.
It can be created in a single line:
conststore=createStore(myComponent);
Step 1: Installation + Setup
You can either install RTK:
along side create-react-app at a project's initial setup, OR
You can now write reducer functions (responsible for updating state based on action.type) and actions (JS objects with type-property) for our Redux Store.
Typically, you would write reducers + actions separately. But in RTK, both can be written in what's called a slice.
Slice –– collection of actions + reducers wrapped up inside the same file.