Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Redux Toolkit is official set of tools for efficient Redux development that simplifies most common Redux use cases, including store setup, creating reducers and immutable state updates.
import { createSlice, configureStore } from '@reduxjs/toolkit';
// Creating slice
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
increment: state => {
state.value += 1;
},
decrement: state => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
}
}
});
// Exporting actions
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
// Creating store
const store = configureStore({
reducer: {
counter: counterSlice.reducer
}
});
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
// Creating async action
export const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await fetch(`/api/users/${userId}`);
return response.json();
}
);
// Slice with async state handling
const userSlice = createSlice({
name: 'user',
initialState: {
data: null,
status: 'idle',
error: null
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchUserById.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchUserById.fulfilled, (state, action) => {
state.status = 'succeeded';
state.data = action.payload;
})
.addCase(fetchUserById.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
});
}
});
Redux Toolkit Advantages:
Redux Toolkit significantly simplifies working with Redux, reduces boilerplate code and provides best practices out of the box.