astarte-platform / astarte-dashboard

Astarte dashboard
http://astarte-platform.org
Apache License 2.0
17 stars 15 forks source link

Device page registering to live events twice #435

Closed Pavinati closed 2 months ago

Pavinati commented 4 months ago

In the current master branch (v1.2.0-dev) the device page registers to device events twice, probably due to a component rerender Screenshot_20240424_145427

Hibe7 commented 2 months ago

I have investigated this issue a little and I found that React version is changed from 17 to 18. This change could be causing the problem because, starting from React 18, Strict Mode intentionally double-renders components to help identify potential issues. As a result, this useEffect is executed twice, leading to the opening of two WebSocket connections and the appearance of duplicate data. Strict mode double-renders components twice just in development mode, in production it renders once. If you want to fix this in development mode we can remove strict mode, that is one solution, or we can use useRef hook and use if statement to prevent second execution of useEffect that I mentioned above.

davidebriani commented 2 months ago

@Hibe7 thanks for the investigation, I guess you found the cause and I assume you verified it by opting out of Strict Mode and seeing that logs don't appear twice anymore.

Regarding the proposed solutions:

For further details, see the React documentation where they explicitly advise on avoiding useRef to prevent Effects from firing: https://react.dev/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development

With that, we verified that the issue is not a bug and it only happens during development, so I'll proceed to close the issue.