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.
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 typesinitialState
: the initial values for our reducerreducers
: 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.
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 name
, initialState
and reducers
parameters.
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