Track the hovered item via one delegated container listener
A data table with 5,000 rows highlights the row under the pointer and shows quick actions for it. Giving every row its own hover state and its own listeners is wasteful. A better design listens once on the container and works out which row the pointer is over (event delegation). Implement a React hook, useHoveredItem, that does this.
function useHoveredItem(attribute?: string): [ref: (element: HTMLElement | null) => void, hoveredId: string | null]
attribute: the attribute that marks an item and holds its id. Defaults to 'data-item-id'.ref: a callback ref. The caller attaches it to the container: <ul ref={ref}>.hoveredId: the value of attribute on the hovered item, or null.mouseover event, which bubbles up from the element under the pointer. Find the closest element (the target itself or an ancestor) that has attribute, and return its attribute value.
null.null. Use mouseleave on the container, or mouseout with a relatedTarget outside the container.function OrdersTable({ orders }) {
const [ref, hoveredId] = useHoveredItem('data-order-id');
return (
<table>
<tbody ref={ref}>
{orders.map((order) => (
<tr key={order.id} data-order-id={order.id}>
<td>{order.customer}</td>
<td>{hoveredId === order.id ? <RowActions order={order} /> : order.total}</td>
</tr>
))}
</tbody>
</table>
);
}
// Pointer over the customer cell of order 'A-17' -> 'A-17'
// Pointer moves down to order 'A-18' -> 'A-18'
// Pointer leaves the table -> null
ref to a list, and reads hoveredId. Some tests count the mouse listeners attached to the list and to its items.mouseover on it. Leaving the container dispatches a bubbling mouseout (with relatedTarget outside the container) and a mouseleave on the container. Pointer events (pointerover) are not dispatched.Object.assign(window, { useHoveredItem }); below “Do not edit below this line”. The tests use it to call your hook.