1

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?

Vmxes
  • 2,329
  • 2
  • 19
  • 34
  • You are using StrictMode. See [this post](https://stackoverflow.com/a/66199206/2873538). – Ajeet Shah Mar 22 '21 at 08:15
  • 1
    @AjeetShah: Thanks, that's the problem. And how to solve this issue properly? I don't want to remove StrictMode and want to develop in development mode. – Vmxes Mar 22 '21 at 09:00
  • You can just ignore it. Because it will behave correctly in production mode. Are you facing any major issue because of this behavior? – Ajeet Shah Mar 22 '21 at 09:01
  • @AjeetShah: Yes, my component doesn't work correctly. I can ignore it but it can make me lazy in the long run. But maybe it is a sign that I have to restructure my code. – Vmxes Mar 22 '21 at 09:15
  • Ok. So, if you have a valid use-case, I have a new question in my mind: "How to disable React.StrictMode in a single component?" I don't yet know the answer but it may be possible. – Ajeet Shah Mar 22 '21 at 09:17

0 Answers0