| name | performance-render-optimization |
| description | null |
Render Optimization
Category: performance · Status: 🟢 Active
When to use
Khi component re-render nhiều lần không cần thiết, list dài giật lag, hoặc DevTools Profiler báo render thừa.
Steps
- Đo trước bằng React DevTools Profiler để biết component nào render thừa.
- Tách state cục bộ xuống component nhỏ nhất; tránh đặt state ở cha khiến cả cây re-render.
- Bọc component con bằng
memo khi props ổn định; truyền callback qua useCallback, object/array qua useMemo.
- Tránh tạo prop mới mỗi render (inline object/array/arrow) làm hỏng memo.
- Dùng
key ổn định, KHÔNG dùng index khi list reorder/insert.
- Cân nhắc tách context hoặc dùng selector để giảm phạm vi cập nhật.
Template
const Row = memo(function Row({ item, onSelect }: Props) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
function List({ items }: { items: Item[] }) {
const onSelect = useCallback((id: string) => { }, []);
return <ul>{items.map((it) => <Row key={it.id} item={it} onSelect={onSelect} />)}</ul>;
}
Example
Good: key ổn định, callback memo hoá, state tách nhỏ.
Avoid: style={{...}} inline cho component đã memo, key={index} với list thay đổi.
Checklist