How To Setup Redux Slices with Redux Toolkit

How To Setup Redux Slices with Redux Toolkit

Redux Toolkit popularity is growing every month. What exactly helps developers to write code faster, easier, more clearly? One of the helpers is createSlice function. createSlice takes an object of reducer functions, a slice name, and an initial state value and lets us auto-generate action types and action creators, based on the names of the reducer functions that we supply. It also helps you organize all of your Redux-related logic for a given slice into a single file.

Redux Toolkit popularity is growing every month. What exactly helps developers to write code faster, easier, more clearly? One of the helpers is createSlice function. createSlice takes an object of reducer functions, a slice name, and an initial state value and lets us auto-generate action types and action creators, based on the names of the reducer functions that we supply. It also helps you organize all of your Redux-related logic for a given slice into a single file.

What is createSlice?

It’s a function that deals with everything you need for each slice, do you remember using createAction and createReducer manually? Now it's available in this specific slice function.

So what the returned object from createSlice contains:

  • name: a parameter that will be the prefix for all of your action types
  • initialState: the initial values for our reducer
  • reducers: it's an object where the keys will become action type strings, and the functions are reducers that will be run when that action type is dispatched.

The other benefit of using createSlice is our files structure. We can put all of our Redux-related logic for the slice into a single file. You'll see how to do it in our tutorial.

Slice configuration

We have made basic Redux configuration with Redux Toolkit. But what is the most important benefit of using Toolkit? Definitely, it’s createSlice function that you will probably use for most application you're developing.

If you don’t want to start from zero, you can use our basic Redux configuration with Redux Toolkit.

To our previous little app with fake authorization, we’re gonna add a feature to show users data to logged user.

Firstly let’s create file src/store/users.js and create our slice:

import { createSlice } from '@reduxjs/toolkit'

// Slice

const slice = createSlice({
    name: 'users',
    initialState: {
        users: []
    },
    reducers: {
        getUsers: (state, action) => {
            state.users = action.payload;
        },
    },
});

export default slice.reducer

That’s basic slice configuration, it contains nameinitialState and reducers parameters.

Adding actions

Now let’s add actions. To keep it clear and simply add it in our slice’s file. We don’t have to write them individually in separate file anymore. We can export all the actions. the reducer, the asynchronous thunk and selector that gives us access to state from any component without using connect.

import { createSlice } from '@reduxjs/toolkit'
+ import { api } from '../api/index'

// Slice

const slice = createSlice({
    name: 'users',
    initialState: {
        users: [],
    },
    reducers: {
        usersSuccess: (state, action) => {
            state.users = action.payload;
            state.isLoading = false;
        },
    },
});

export default slice.reducer

// Actions

+ const { usersSuccess } = slice.actions

+ export const fetchUsers = () => async dispatch => {
+    try {
+        await api.get('/users')
+            .then((response) => dispatch(usersSuccess(response.data)))
+    }
+    catch (e) {
+        return console.error(e.message);
+    }
+}

react front-end-development redux software-development startup redux toolkit

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Offshore Software Development - Best Practices

To make the most out of the benefits of offshore software development, you should understand the crucial factors that affect offshore development.

5 Core Criteria for Selecting Software Development Company - TopDevelopers.co

Check out these five criteria for the selection of your software vendor, and you will never regret having the wrong quality product made for you.

Why You Should Not Learn React, Angular or Vue as a Beginner in Front-End Web Development

Do not follow the hype behind Frameworks and Libraries. Why You Should Not Learn React, Angular or Vue as a Beginner in ... what should I learn? maybe front-end web development, or maybe Cloud ...

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms? React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. **[Hire...