// Action creators are generated for each case reducer function exportconst { increment, decrement, incrementByAmount } = counterSlice.actions;
exportdefault counterSlice.reducer;
In this example, we define a slice of the Redux store called counter. It has an initial state of {value: 0} and reducer functions: increment, decrement and incrementByAmount.
incrementByAmount takes a payload as an argument and increments the state by that amount.
Export action creators from the slice. These are functions that dispatch actions to the reducer. We can use these functions in our React components to update the state.
Add Slice to Redux Store
Now we can add the reducers we defined from slice to the Redux store. In store.js:
In this component, we use the useSelector hook to access the state from the Redux store
1 2
// getting state value from Redux store using useSelector hook const count = useSelector((state) => state.counter.value);
We use the useDispatch hook to get the dispatch function. When the “Increment” or “Decrement” buttons are clicked, the corresponding actions are dispatched, updating the state through the reducer defined in the counterSlice.js file.
1 2 3 4 5 6 7 8 9 10 11
// import the actions from slice import { decrement, increment, incrementByAmount } from"./counterSlice";
// get dispatch hook const dispatch = useDispatch();
// dispatch action dispatch(increment());
// dispatch action with payload dispatch(incrementByAmount(Number(incrementAmount) || 0));