1. Các bước làm
1-1. Import useReducer
import { useReducer } from 'react'
1-2. Khởi tạo giá trị ban đầu
const initialState = 0
1-3. Tạo hàm reducer
- Hàm này nhận 2 tham số
- Tham số 1 là state muốn thay đổi giá trị
- Tham số 2 là action
- Tùy vào loại action mà thay đổi state tương ứng
const reducer = (state, action) => {
switch (action) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
case 'reset':
return initialState
default:
return state
}
}
1-4. Sử dụng useReducer
- Hàm useReducer nhận 2 tham số
- Tham số 1 là hàm reducer ở bước 1-3
- Tham số 2 là biến initialState ở bước 1-2
- Hàm useReducer trả về mảng 2 phần tử
- Phần tử 1 là giá trị của state
- Phần tử 2 là hàm để thay đổi state
const [count, dispatch] = useReducer(reducer, initialState)
return (
<>
<h3>Count: {count}</h3>
<button onClick={() => dispatch('increment')}>
Increment
</button>
<button onClick={() => dispatch('decrement')}>
Decrement
</button>
<button onClick={() => dispatch('reset')}>
Reset
</button>
</>
)
2. Toàn bộ file
import React, { useReducer } from 'react'
const initialState = 0
const reducer = (state, action) => {
switch (action) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
case 'reset':
return initialState
default:
return state
}
}
export default function HookCounter() {
const [count, dispatch] = useReducer(reducer, initialState)
return (
<>
<h3>Count: {count}</h3>
<button onClick={() => dispatch('increment')}>Increment</button>
<button onClick={() => dispatch('decrement')}>Decrement</button>
<button onClick={() => dispatch('reset')}>Reset</button>
</>
)
}
3. Demo