Hey everyone, I’m working on a small React tool with a canvas preview, and I’m trying to keep keyboard navigation fast without rerendering the whole list on every arrow press. I moved the selected item into a ref for speed, but now the Enter key sometimes opens the previously selected row instead of the current one.
function Picker({ items }) {
const [selected, setSelected] = React.useState(0);
const selectedRef = React.useRef(selected);
React.useEffect(() => {
selectedRef.current = selected;
}, [selected]);
React.useEffect(() => {
function onKeyDown(e) {
if (e.key === "ArrowDown") setSelected(i => Math.min(i + 1, items.length - 1));
if (e.key === "Enter") openItem(items[selectedRef.current]);
}
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [items]);
}
What is the clean way to avoid this stale selection bug without giving up the performance win from not rebuilding the handler on every state change?
MechaPrime