React từ cơ bản đến nâng cao
Trang chủ / Module 7
🧩 Module 7 / 22 · 4 ngày 📅 Tuần 4 ●●○○ Trung bình

Thiết kế component: nâng state, composition và compound component

Đặt state ở đâu, chia sẻ state giữa component anh em, tránh prop drilling bằng composition, compound component và component vừa controlled vừa uncontrolled.

Lifting stateCompositionCompoundControlled props
📌 Vì sao module này quan trọng

Phần lớn code React khó sửa không phải vì thiếu thư viện mà vì state đặt sai chỗ và component nhận 20 props. Các kỹ thuật trong module này là thứ phân biệt người "biết React" với người thiết kế được component cho cả team dùng.

🎯 Mục tiêu học tập

  • Chọn đúng vị trí cho state: component chung gần nhất
  • Giảm prop drilling bằng composition (children, slot props) trước khi nghĩ tới Context
  • Viết compound component (<Tabs>, <Tabs.List>, <Tabs.Panel>)
  • Viết component hỗ trợ cả controlled và uncontrolled giống thẻ input gốc

Nâng state lên (lifting state up)

Hai component cần cùng một dữ liệu → đưa state lên component cha chung gần nhất, truyền giá trị xuống bằng props và truyền hàm cập nhật xuống bằng callback.

function Accordion() {
  const [activeIndex, setActiveIndex] = useState(0);   // state ở cha
  return (
    <>
      <Panel title="Giới thiệu" isActive={activeIndex === 0} onShow={() => setActiveIndex(0)}>...</Panel>
      <Panel title="Giá" isActive={activeIndex === 1} onShow={() => setActiveIndex(1)}>...</Panel>
    </>
  );
}
function Panel({ title, children, isActive, onShow }) {
  return (
    <section>
      <h3>{title}</h3>
      {isActive ? <p>{children}</p> : <button onClick={onShow}>Xem</button>}
    </section>
  );
}

Ngược lại, state chỉ một component dùng thì đặt càng thấp càng tốt (colocation): ít component phải render lại, dễ xoá code.

Composition trước Context

Prop drilling (truyền user qua 5 tầng chỉ để tầng cuối dùng) thường giải được bằng cách để cha truyền thẳng JSX đã có dữ liệu xuống.

// ❌ Layout không dùng user nhưng phải nhận và truyền tiếp
<Layout user={user}><Header user={user}><Avatar user={user} /></Header></Layout>

// ✅ Composition: Layout và Header chỉ nhận chỗ trống (slot)
<Layout header={<Header right={<Avatar user={user} />} />}>
  <Dashboard />
</Layout>

function Layout({ header, children }) {
  return <div className="layout">{header}<main>{children}</main></div>;
}

Lợi ích phụ: khi state trong Layout đổi, children truyền từ ngoài vào không render lại (vì element được tạo ở cha, tham chiếu không đổi) — một kỹ thuật tối ưu hiệu năng miễn phí (Module 17).

Compound component

Một nhóm component phối hợp, chia sẻ state ngầm qua Context. Người dùng tự sắp xếp cấu trúc, API gọn hơn nhiều so với truyền mảng cấu hình.

const TabsContext = createContext(null);

export function Tabs({ defaultValue, children }) {
  const [value, setValue] = useState(defaultValue);
  return <TabsContext value={{ value, setValue }}>{children}</TabsContext>;  // React 19: <Context> thay <Context.Provider>
}
Tabs.List = function TabsList({ children }) {
  return <div role="tablist">{children}</div>;
};
Tabs.Trigger = function TabsTrigger({ value, children }) {
  const ctx = useContext(TabsContext);
  return (
    <button role="tab" aria-selected={ctx.value === value} onClick={() => ctx.setValue(value)}>
      {children}
    </button>
  );
};
Tabs.Panel = function TabsPanel({ value, children }) {
  const ctx = useContext(TabsContext);
  return ctx.value === value ? <div role="tabpanel">{children}</div> : null;
};

// Sử dụng
<Tabs defaultValue="info">
  <Tabs.List>
    <Tabs.Trigger value="info">Thông tin</Tabs.Trigger>
    <Tabs.Trigger value="reviews">Đánh giá</Tabs.Trigger>
  </Tabs.List>
  <Tabs.Panel value="info"><ProductInfo /></Tabs.Panel>
  <Tabs.Panel value="reviews"><Reviews /></Tabs.Panel>
</Tabs>

Controlled và uncontrolled trong cùng một component

Component tốt cho phép cha chọn: tự quản lý (defaultValue) hoặc để cha điều khiển (value + onChange) — đúng như thẻ <input>. Đây là cách Radix UI, React Aria làm.

function useControllableState({ value, defaultValue, onChange }) {
  const [inner, setInner] = useState(defaultValue);
  const isControlled = value !== undefined;
  const current = isControlled ? value : inner;
  const setValue = next => {
    const v = typeof next === 'function' ? next(current) : next;
    if (!isControlled) setInner(v);
    onChange?.(v);
  };
  return [current, setValue];
}

function Toggle({ pressed, defaultPressed = false, onPressedChange, children }) {
  const [on, setOn] = useControllableState({ value: pressed, defaultValue: defaultPressed, onChange: onPressedChange });
  return <button aria-pressed={on} onClick={() => setOn(v => !v)}>{children}</button>;
}

Checklist thiết kế API component

  • Đặt tên props theo nghĩa nghiệp vụ, dùng chung quy ước của HTML (disabled, onChange, value).
  • Chuyển các props còn lại xuống phần tử gốc (...rest) để người dùng thêm aria-*, data-*, className.
  • Variant dùng union rõ ràng (variant="primary" | "ghost") thay vì nhiều boolean (isPrimary, isGhost).
  • Hơn 8-10 props → xem lại: có thể tách thành compound component hoặc nhận children.
  • Không để component con tự fetch dữ liệu nếu nó là component trình bày (presentational) dùng lại nhiều nơi.

🚩 Sai lầm hay gặp

  • Đưa mọi state lên App 'cho chắc' → mỗi lần gõ phím cả app render lại.
  • Dùng Context ngay khi gặp prop drilling 2 tầng — composition thường đủ.
  • Component vừa đọc value vừa có state riêng copy từ value → hai nguồn sự thật lệch nhau.

🏋️ Bài tập thực hành

Thư viện mini: Tabs, Accordion, Select

Viết 3 compound component, mỗi cái hỗ trợ cả controlled và uncontrolled, có role/aria đúng và điều khiển bằng phím mũi tên. Viết trang demo dùng mỗi chế độ.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Tôi chọn được vị trí đúng cho state trong một màn hình cụ thể
  • Tôi giải được prop drilling bằng composition
  • Tôi tự viết được compound component
  • Tôi viết được component hỗ trợ cả controlled và uncontrolled