Skip to main content

Command Palette

Search for a command to run...

React hook - useReducer - simple State & Action

Updated
2 min readView as Markdown
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

ReactJS

Part 7 of 19

ReactJS là một thư viện JavaScript mã nguồn mở được thiết kế bởi Facebook để tạo ra những ứng dụng web hấp dẫn, nhanh và hiệu quả với mã hóa tối thiểu. Series hướng dẫn học ReactJS cơ bản.

Up next

React hook - useContext - P5

Ta có cấu trúc component như hình trên useContext giúp chúng ta gửi data từ AppComponent tới ComponentC mà không cần phải truyền qua component trung gian A và B Bài này sẽ hướng dẫn sử dụng nhiều useContext lồng nhau 1. AppComponent - component gửi ...

More from this blog

KenTrung VN

23 posts

Mình mới ba mấy tuổi thôi mà đứng dậy nhanh quá đã hơi chóng mặt 🤪🤪🤪