# React hook - useReducer - simple State & Action

## 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
<iframe src="https://codesandbox.io/embed/react-hook-usereducer-3glg8?autoresize=1&fontsize=12&hidenavigation=1&theme=dark"
     style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
     title="React hook - useReducer"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
