Redux & Toolkit
If you haven't worked with Redux, it's highly recommended (possibly indispensable!) to read through the (amazing) official documentation and/or watch this free video tutorial series.
As minimal as Redux is, the challenge it addresses - app state management - is a complex topic that is too involved to properly discuss here.
Usage
1) Creating a dedicated slice folder
Let's start creating a slice to manage our Homescreen data and call it HomescreenSlice
.
An empty folder .../Homescreen/slice/
2) Declaring your state
Redux manages your state so we have to declare our state first. We can create a types.ts
file in our slice. Types are crucial for efficient and safe development. Your compiler and code completion will understand the shape of your state and help you code the rest of your project faster and safer.
.../Homescreen/slice/types.ts
.../Homescreen/slice/types.ts
3) Updating your Redux State
Now that you are adding another slice
to your state you also need to declare this in your types/RootState.ts
file. Since we are adding Redux slices asynchronously with Redux-injectors, the compiler cannot tell what the Redux State is during the build time. So, we explicitly declare them types/RootState.ts
file:
types/RootState.ts
types/RootState.ts
4) Creating your slice
Fortunately, Redux Toolkit handles most of the work for us. To create our slice, we create a index.ts
file in our folder as well. This will be responsible for:
Our slice's initial state
Actions we can trigger
Reducers that decide how the state will change, given the action received
.../Homescreen/slice/index.ts
.../Homescreen/slice/index.ts
5) Adding the slice to your Redux Store
Let's add our slice to the redux state. We can write a simple 'hook' and use it in our component(whichever you want)
.../Homescreen/slice/index.ts
.../Homescreen/slice/index.ts
5) Using the slice in your component
Let's use the hook we created above in our component
.../Homescreen/index.tsx
.../Homescreen/index.tsx
🎉 Good News: You don't need to write this boilerplate code by hand, the slice
generator will generate it for you. ✓
yarn generate slice
Last updated