createSlice
internally uses createAction
and createReducer
, so you may also use Immer to write “mutating” immutable updates.
store.js
import {configureStore, createSlice} from '@reduxjs/toolkit';
const initialState = {counter: 0, showCounter: true};
const counterSlice = createSlice({
name: "counter",
initialState: initialState,
reducers: {
increment(state, action) {
state.counter += action.payload
},
decrement(state, action) {
state.counter -= action.payload
},
toggle(state, action) {
state.showCounter = !state.showCounter
}
}
})
export const counterActions = counterSlice.actions;
export const store = configureStore({
reducer: {
counter: counterSlice.reducer
}
});
index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';
import reportWebVitals from './reportWebVitals';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
reportWebVitals();
Counter.js
import {useSelector, useDispatch} from 'react-redux';
import {counterActions} from "../app/store";
function Counter() {
const counter = useSelector(state => state.counter.counter);
const showCounter = useSelector(state => state.counter.showCounter);
const dispatch = useDispatch();
return (
<div>
<div>
{showCounter && <div>Counter : {counter}</div>}
</div>
<div>
<button onClick={() => dispatch(counterActions.increment(1))}>+1</button>
<button onClick={() => dispatch(counterActions.decrement(1))}>-1</button>
<button onClick={() => dispatch(counterActions.toggle())}>Toggle</button>
</div>
</div>
);
}
export default Counter;
References
https://redux-toolkit.js.org/api/createslice