1

Many of you might have heard of GraphQL. It provides QUERY and MUTATION. Also it supports SUBSCRIPTION as 100% replacement of web socket. I'm a big fan of GraphQL and hooks. Today I faced an issue with useSubscription which is a hook version of SUBSCRIPTION. When this subscription is fired, a React component is re-rendered. I'm not sure why it causes re-rendering.

import React from 'react'
import { useSubscription } from 'react-apollo'

const Dashboard = () => {
  ...
  useSubscription(query, {
    onSubscriptionData: data => {
      ...
    }
  })

  render (
    <>
      Dashboard
    </>
  )
}

Actually useSubscription's API doc doesn't say anything about this re-rendering now. It would be really appreciated if you provide me a good solution to preventing the re-rendering.

Thanks!

4
  • When you receive new data from onSubscriptionData, your component will be re-rendered. It's like a parent pass a prop to its child, when you update this prop, the child component will be re-rendered.
    – Michael
    May 19, 2020 at 3:48
  • Hi @Michael, could tell me how to prevent the re-rendering?
    – tronx.dev
    May 19, 2020 at 6:52
  • why do you want to prevent re-rendering?
    – Michael
    May 19, 2020 at 7:18
  • In the subscription, a Global variable is updated. It is used for calculations, but no triggering re-render. Eventually the global variable should be updated without re-rendering via the subscription.
    – tronx.dev
    May 19, 2020 at 10:36

2 Answers 2

3

Just put your subscription in separate component as this guy did, and return null, now your root component won't rerender

function Subscription () {
  const onSubscriptionData = React.useCallback(
    handleSubscription,  // your handler function
    [])

  useSubscription(CHAT_MESSAGE_SUBSCRIPTION, {
    shouldResubscribe: true,
    onSubscriptionData
  })

  return null
}

// then use this component
<Subscription />
0

In my experience, there is no way to prevent re-render when receiving new data in onSubscriptionData. If your global data is used for calculations, you should use useMemo for you global variable. On the other hand, you should consider do you need put your variable in onSubscriptionData? Are there other ways? Did you use useSubscription in right component? If your have to do that, you have to accept extra rendering.
Hopefully, my answer is helpful for your situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.