Để sử dụng slice, trước tiên, ta cần thay thế reducer thông thường của store thành slice reducer như sau:
// app/store.js
import { configureStore } from "@reduxjs/toolkit"
import counterReducer from "./counterSlice"
export default configureStore({ reducer: counterReducer })Tất nhiên là ta cũng cần phải cung cấp store này cho toàn bộ ứng dụng:
<Provider store={store}>
<App />
</Provider>Sau đó, gọi sử dụng các action creator ở trong component cần sử dụng store như sau:
// Counter.jsx
import { useSelector, useDispatch } from "react-redux"
import { increment, decrement } from "./counterSlice"
function Counter() {
const count = useSelector((state) => state.count)
const dispatch = useDispatch()
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch(increment(1))}>+1</button>
<button onClick={() => dispatch(decrement(1))}>-1</button>
</div>
)
}
export default Counter