I will be keeping the feature naming for the counter, and will be renaming the file from counter.js.
The ability to call a reducer with a function also feels more in line with the rest of the coding we do in React. A basic createSlice methods takes in the following: name: which is name of the slice for reference initialState: the initial state of the reducer reducers: contains all the actions to mutate the reducer state Lets update the repo to a slice. Once the concept of the setup was understood it feel a lot simpler, and I like simple.
It is a helper method to generate a store slice. Redux Toolkit simplifies most Redux tasks like setting up the store, creating reducers and performing immutable updates. The same payload from above will still be used.
A Reducer with createSlice For the action ADDTOUSERFOODS, updateFoods will be used in our code below. Here’s how we can refactor our reducer above and end up with a very clean code solution. createSlice is a higher order function that accepts an initial state, an object full of reducer functions and a slice name. Redux Toolkit can replace a series of actions/reducers/constants using its createSlice API. Redux Toolkit, also known as the reduxjs/redux-toolkit package, contains packages and functions that are essential for building a Redux app. Redux Toolkit The better way is to use createSlice from the Redux Toolkit. This method returns an object with reducers and actions that can be used for injection with other middleware. ConfidenceĪs the code I was working on was refactored to use the Redux Toolkit and the createSlice functionality, there was a relieved feeling and a sense of confidence that my code was cleaner. The counterSlice file uses the createSlice method from RTK. Import )Īs shown, the dispatch to call the reducer is now cleaner, simply calling it as a function and sending the payload rather than having to construct an object.