In Redux Toolkit, when you directly mutate the state like you're doing in your increment
reducer, Redux itself won't be able to detect that change because it's based on immutability.
To update the state correctly, you should return a new object from your reducers instead of modifying the existing state object. Here's how you can modify your increment
reducer function to correctly update the state:
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
return { ...state, value: state.value + 1 };
},
},
});
export const { increment } = counterSlice.actions;
export default counterSlice.reducer;
By spreading the existing state and only modifying the part that needs to be updated (value
in this case), you're creating a new object with the updated value. This way, Redux Toolkit can properly detect the state change and trigger re-renders in your React components.
After making this change, dispatching the increment
action should update the state correctly in your Redux store, and your components should reflect this updated state.
Let me know if you have any more questions or if you need further clarification!