Per-key counts hook with total and stable increment actions
A chat app shows reaction counts under every message (👍 3, ❤️ 1). Each message renders a row of reaction buttons wrapped in React.memo, so the buttons must receive handlers whose identity never changes. Otherwise every new reaction re-renders every button row. Implement a React hook, useTally, that keeps a count per key and exposes stable actions.
function useTally(initial?: Record<string, number>): {
counts: Record<string, number>;
total: number;
actions: {
increment: (key: string, by?: number) => void;
decrement: (key: string, by?: number) => void;
reset: () => void;
};
}
initial defaults to {}. You can assume its values are positive integers. Only the value from the first render is used.counts maps each key to its count. Keys with a count of 0 are never present.total is the sum of all counts.increment(key, by = 1) adds by to the key, creating it if needed.decrement(key, by = 1) subtracts by, but never below 0. A key that reaches 0 is removed from counts. Decrementing a key that is not present does nothing.by must be a positive, finite number. Any other value (0, negative, NaN, Infinity) is ignored.reset() restores the counts from the first render.counts object.actions is the same object on every render (and so are its functions). A React.memo child that receives actions must not re-render when the counts change.const { counts, total, actions } = useTally({ thumbsUp: 3, heart: 1 });
// counts { thumbsUp: 3, heart: 1 }, total 4
actions.increment('laugh'); // { thumbsUp: 3, heart: 1, laugh: 1 }, total 5
actions.increment('heart', 4); // { thumbsUp: 3, heart: 5, laugh: 1 }, total 9
actions.decrement('laugh'); // { thumbsUp: 3, heart: 5 } ('laugh' removed)
actions.decrement('thumbsUp', 10); // { heart: 5 } (never below 0)
actions.decrement('wow'); // nothing changes
actions.increment('heart', -2); // ignored
actions.reset(); // { thumbsUp: 3, heart: 1 }
ReactDOM.flushSync.actions to a React.memo child and counts how many times the child renders.Object.assign(window, { useTally }); below “Do not edit below this line”. The tests use it to call your hook.