Redux Toolkit là một công cụ giúp triển khai Redux dễ dàng hơn.

Cài đặt Redux Toolkit như sau:

  • NPM:

    npm install @reduxjs/toolkit
  • Yarn:

    yarn add @reduxjs/toolkit

Để thiết lập ứng dụng Redux sử dụng Redux Toolkit, ta cần thực hiện những bước sau:

  • Tạo ra slice của một tính năng nào đó, bao gồm một slice reducer và các action creator (xem thêm Creating the Redux Slice).
  • Cấu hình store dựa trên slice reducer và gọi sử dụng các action creator của slice (xem thêm Using the Redux Slice).

Example

Giả sử ta cần xây dựng một ứng dụng counter bằng Redux Toolkit.

Trước tiên, tạo ra slice của counter như sau:

// features/counter/counterSlice.js
import { createSlice } from "@reduxjs/toolkit"
 
const counterSlice = createSlice({
    name: "counter",
    initialState: { count: 0 },
    reducers: {
        increment: (state, action) => {
            state.count += action.payload
        },
        decrement: (state, action) => {
            state.count -= action.payload
        }
    }
})
 
export const { increment, decrement } = counterSlice.actions
 
export default counterSlice.reducer

Sau đó, ta cần cấu hình store dựa trên slice reducer của slice vừa tạo:

// app/store.js
import { configureStore } from "@reduxjs/toolkit"
import counterReducer from "../features/counter/counterSlice"
 
const store = configureStore({ reducer: counterReducer })
 
export default store

Cuối cùng, gọi sử dụng các action creator của slice ở trên trong component như sau:

// features/counter/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
list
from [[Redux Toolkit App Structure]]
sort file.ctime asc

Resources