Hook managing a list by key with upsert, move, and remove
A ride-hailing dispatcher screen lists live trips. A socket pushes trip updates: some are new trips, most are status changes for trips already on screen. The dispatcher can also drag a trip to the top and dismiss finished ones. Every trip has a unique id, so the list is best managed by key instead of by index. Implement a React hook, useKeyedList, that does this.
function useKeyedList<T>(
initial: T[],
getKey: (item: T) => string,
): {
items: T[];
upsert: (item: T) => void;
remove: (key: string) => void;
move: (key: string, toIndex: number) => void;
clear: () => void;
}
initial: the starting items. Only the value from the first render is used. You can assume their keys are unique.getKey: returns the unique key of an item. Callers usually pass an inline function, so it can be a new function on every render.upsert(item): if an item with the same key exists, replace it at the same position. Otherwise append it to the end.remove(key): remove the item with that key.move(key, toIndex): move the item so that it ends up at toIndex in the resulting list. Clamp toIndex to the valid range (below 0 means first, past the end means last). You can assume toIndex is an integer.clear(): remove every item.items array or the items in it. Items that an action does not touch keep their identity (same object).remove or move with an unknown key, move to the index the item is already at, clear on an empty list, and upsert of the exact object (===) already stored under that key.upsert, remove, move and clear keep the same identity across renders, even when getKey changes. They always use the latest getKey.const trips = useKeyedList(
[{ id: 't1', status: 'requested' }, { id: 't2', status: 'en route' }],
(trip) => trip.id,
);
trips.upsert({ id: 't3', status: 'requested' });
// t1 requested, t2 en route, t3 requested
trips.upsert({ id: 't1', status: 'picked up' });
// t1 picked up, t2 en route, t3 requested (replaced in place)
trips.move('t3', 0);
// t3, t1, t2
trips.move('t3', 50);
// t1, t2, t3 (clamped to the last index)
trips.remove('t2');
// t1, t3
trips.remove('t9');
// unknown key: items is the same array as before
ReactDOM.flushSync.===) of the items array, of individual items, and of the action functions.Object.assign(window, { useKeyedList }); below “Do not edit below this line”. The tests use it to call your hook.