npm install @reduxjs/toolkit react-redux
import {store, Provider, configureStore, counterSlice, useSelector, useDispatch, actions...}
/store.js
!import { configureStore } from '@reduxjs/toolkit'
!import counterReducer from '../features/counter/counterSlice'
export const store = configureStore({
reducer: {
counter: counterReducer,
},
})
/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
!import { store } from './app/store'
!import { Provider } from 'react-redux'
ReactDOM.render(
!<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
/counterSlice.js
!import { createSlice } from '@reduxjs/toolkit'
const initialState = {
value: 0,
}
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
},
})
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
import React from 'react'
! import { useSelector, useDispatch } from 'react-redux'
! import { decrement, increment } from './counterSlice'
export function Counter() {
! const count = useSelector((state) => state.counter.value)
const dispatch = useDispatch()
return (
<div>
<div>
<button
aria-label="Increment value"
onClick={() => !dispatch(increment())}
>
Increment
</button>
<span>{count}</span>
<button
aria-label="Decrement value"
onClick={() => !dispatch(decrement())}
>
Decrement
</button>
</div>
</div>
)
}