Course Content
Introduction to Redux
Introduction to Redux
Understanding Slice
We can create a slice by manually defining reducers, actions, and the action objects for a feature, however, that is not the convention as it's a tedious process, and there is a better alternative.
The createSlice
function creates and returns a new slice object which contains the actions, action creator(s), and slice reducer(s):
The above is an example of a simple Todo feature slice. The createSlice
function automatically generates the action creators for us, which can then be used for dispatches from the React components.
Recall that an action is an object with a type
key and an optional payload
key. An action creator is a function that generates and returns an action object, we use these to ease the process.
We can manually create action objects like this:
However, createSlice
creates action creators for us based on the actions we passed in the createSlice
argument object. For example in the above case, the addTodo
generated by createSlice
may look like this:
The first part, 'todo'
, is from the name
of the slice, while the second part, addTodo
, is the name of the action's key. Hence it is todo/addTodo
.
To sum up, the following is the complete code of todosSlice.js
:
Since the generated action creators and the slice reducers will be needed in index.js
and other React component files, we need to export them, in the end, to make them usable.
Thanks for your feedback!