I'm quite new to React and try to use useRef to store the currently selected item in a list. It's an AutoCompleteDialog
, where the component gets all available items, a filter string, an open state, a position, and a selectionMove event.
The keydown
events are captured in the parent component and this event is propagated to the AutoCompleteDialog
via the selectionMove
prop.
I have the following code:
export const AutoCompleteDialog = ({items, filter, open=false, top=0, left=0, selectionMove={dir:0}}) => {
const position = {top: top, left:left};
const selectedIndex = useRef({idx:0});
console.log('Render');
if (selectionMove.dir === -1) {
selectedIndex.current.idx = selectedIndex.current.idx + 1;
} else if (selectionMove.dir === 1) {
selectedIndex.current.idx = selectedIndex.current.idx - 1;
}
console.log('index: ' + selectedIndex.current.idx);
My problem is that it seems the component increases the useRef variable twice. The "Render" string is displayed once, but the index value is increased by 2 instead of 1.
The console output of the above code is:
...
Render
index: 7
Render
index: 9
Render
index: 11
I already removed all other usages of selectedIndex
but still, it counts as two.
What can be the problem?