| name | react-event-handling |
| description | null |
Event Handling
Category: react · Status: 🟢 Active
When to use
Khi viết handler cho sự kiện DOM/UI trong component React.
Steps
- Đặt tên handler theo
handle<Subject><Event> (vd handleSubmitForm).
- Type chính xác event (
React.ChangeEvent<HTMLInputElement>, React.MouseEvent).
- Tránh tạo hàm nặng/inline tốn kém trong JSX; tách ra hoặc
useCallback khi cần.
- Debounce/throttle cho input search, scroll, resize tần suất cao.
preventDefault/stopPropagation khi cần; truyền tham số qua closure gọn.
Template
const handleSearchChange = useMemo(
() => debounce((value: string) => onSearch(value), 300),
[onSearch],
);
<input onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
handleSearchChange(e.target.value)} />
Example
Good: handleSearchChange debounce 300ms, event được type, prop callback ổn định.
Avoid: onChange={() => doHeavyWork()} inline mỗi render; không debounce ô search.
Checklist