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 Homepage data and call it HomepageSlice.

An empty folder .../Homepage/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.

.../Homepage/slice/types.ts

/* --- STATE --- */
export interface HomepageState {
  username: string;
  // declare what you want in your Homepage state
}

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

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

.../Homepage/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)

.../Homepage/slice/index.ts

5) Using the slice in your component

Let's use the hook we created above in our component

.../Homepage/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

Was this helpful?