Quay lại danh sách bài viết

React Hooks Tìm hiểu Sâu: Phần 2 - useContext và useReducer

Xuất bản ngày
bởi Nguyễn Công Dũng
reacthooksjavascripttutorial

React Hooks Tìm hiểu Sâu: Phần 2 - useContext và useReducer

Chào mừng đến Phần 2 của loạt bài React Hooks! Hôm nay chúng ta sẽ khám phá useContextuseReducer cho các tình huống quản lý state nâng cao hơn.

useContext Hook

Hook useContext cho phép bạn sử dụng các giá trị context mà không cần prop drilling:

TypeScript
import { createContext, useContext } from 'react';
 
const ThemeContext = createContext('light');
 
function ThemedButton() {
  const theme = useContext(ThemeContext);
 
  return (
    <button className={`btn-${theme}`}>
      Theme hiện tại: {theme}
    </button>
  );
}

Khi nào sử dụng

  • Chia sẻ dữ liệu qua nhiều components
  • Tránh prop drilling
  • Global state không thay đổi thường xuyên

useReducer Hook

useReducer giống như useState nhưng cho logic state phức tạp:

TypeScript
import { useReducer } from 'react';
 
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}
 
function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
 
  return (
    <div>
      <p>Số đếm: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
}

Lợi ích

  • Cập nhật state dự đoán được
  • Dễ test hơn
  • Tốt hơn cho logic state phức tạp

Các bước tiếp theo

Trong Phần 3, chúng ta sẽ học về custom hooks và cách xây dựng logic có thể tái sử dụng!