Hook managing a Set selection with select-all and auto-pruning
An email client lets you tick messages and then archive or delete them all at once. The header checkbox selects every message, shows a dash when only some are selected, and the selection must never contain a message that is no longer in the list (because it was deleted or filtered out). Implement a React hook, useSelectionSet, that manages this selection as a JavaScript Set.
function useSelectionSet<K>(
ids: readonly K[],
initialSelected?: Iterable<K>,
): {
selected: ReadonlySet<K>;
isSelected: (id: K) => boolean;
toggle: (id: K) => void;
selectAll: () => void;
clear: () => void;
allSelected: boolean;
indeterminate: boolean;
}
ids is the list of ids that can be selected, in display order. Ids are unique and compared with ===. Callers usually pass a new array on every render (for example messages.map((m) => m.id)).initialSelected that are in ids. Others are ignored. With no initialSelected, nothing is selected.selected is a Set. Never mutate a Set you have returned: every change produces a new Set.Set object (so useMemo/React.memo consumers do not re-run).toggle(id) selects id if it is not selected and deselects it otherwise. Ids that are not in ids are ignored.selectAll() selects every id in ids. clear() deselects everything.ids, it is dropped from the selection in the same render (do not show it for one render and remove it in an effect). If it comes back later, it is not selected.ids array with the same ids in the same order changes nothing, so selected keeps the same Set.isSelected(id) tells whether id is selected.allSelected is true when ids is not empty and every id is selected. indeterminate is true when at least one id, but not every id, is selected.toggle, selectAll and clear keep the same identity across renders.const ids = ['m1', 'm2', 'm3'];
const s = useSelectionSet(ids, ['m2', 'm9']);
// s.selected: Set { 'm2' } ('m9' is not in the list)
// s.indeterminate: true, s.allSelected: false
s.toggle('m1'); // Set { 'm2', 'm1' }
s.toggle('m2'); // Set { 'm1' }
s.toggle('m42'); // ignored, same Set
s.selectAll(); // Set { 'm1', 'm2', 'm3' }, allSelected: true
s.selectAll(); // nothing changes, same Set
// Next render: m1 was deleted, so ids is ['m2', 'm3'].
// s.selected: Set { 'm2', 'm3' }, allSelected: true
s.clear(); // Set {}, indeterminate: false
ids happen inside ReactDOM.flushSync. Some tests compare Set objects by reference and check the selection in every committed render.Object.assign(window, { useSelectionSet }); below “Do not edit below this line”. The tests use it to call your hook.