Inside StrictMode useSubscription subscribes twice
See original GitHub issueIntended outcome:
useSubscription should subscribe only once when run inside <StrictMode>
Actual outcome:
useSubscription subscribes twice to the same subscription. I think that this happens because <StrictMode>
intentionally runs component bodies twice. I suppose that same thing could happen in concurrent mode too.
This results in double network traffic. Also, the second subscription won’t get unsubscribed when the useSubscription is unmounted.
This can be inspected on chrome network tab: in the picture, id 15 and 16 are the single useSubscription and receive the same data. After unmount the id 16 was closed and id 15 was left receiving data(not pictured).
I am not familiar with apollo-client codebase, but I think that this is result of the following line being run in function body instead of inside useEffect: https://github.com/apollographql/apollo-client/blob/23b17fa7283b21966d1c633c52b848f12b4a211e/src/react/hooks/useSubscription.ts#L44
How to reproduce the issue:
Any subscription should behave the same when run in StrictMode.
const SubComponent = ({vesselId}) => {
const { data } = useSubscription(vesselStatus, {
variables: { vesselId }
});
return null;
}
<StrictMode>
<SubComponent vesselId="245" />
</StrictMode>
Workaround is to not use StrictMode, but I’m afraid that will result in code that breaks when concurrent mode lands in React.
Versions
System: OS: macOS 10.15.3 Binaries: Node: 12.16.1 - ~/.nvm/versions/node/v12.16.1/bin/node Yarn: 1.22.0 - ~/.nvm/versions/node/v12.16.1/bin/yarn npm: 6.13.4 - ~/.nvm/versions/node/v12.16.1/bin/npm Browsers: Chrome: 80.0.3987.132 Firefox: 73.0.1 Safari: 13.0.5 npmPackages: @apollo/client: ^3.0.0-beta.39 => 3.0.0-beta.39 @apollo/link-ws: ^2.0.0-beta.3 => 2.0.0-beta.3 apollo-server-express: ^2.11.0 => 2.11.0 npmGlobalPackages: apollo-codegen: 0.20.2 apollo: 2.24.0
Issue Analytics
- State:
- Created 4 years ago
- Reactions:58
- Comments:37
Top GitHub Comments
There is a reason for strict mode rendering twice. It is to prevent bugs in the coming concurrent mode. So this should be fixed in apollo-client.
That might hide the symptoms, but having to run a production build when doing active development would get tedious and annoying real fast. We need a real solution for this issue.