How granular should Relay/Apollo fragments be?
Asked Answered
L

2

6

I'm using GraphQL + Relay in my app and find myself wrapping almost every component with createFragmentContainer, including those very low in the DOM hierarchy (usually functional components).

Is that the right way to use fragments? I'm wondering what are the guidelines for when to wrap components in fragment containers? Seems redundant to wrap a component when it only needs one field and I can pass that data from the parent via props.

I'm using Relay but I think the concepts are similar to Apollo as well.

Lishalishe answered 30/10, 2018 at 22:56 Comment(0)
F
4

Yes, it is. Instead of querying all the data on root component and pass to others as props, you should create fragment containers and each of this component query its own data. And due to relay data masking, these data from fragments can only be seen inside the component that required it.

Maybe this is a good reading: https://medium.com/entria/relay-apollo-anti-pattern-d9f4dea47738

And this on Data Masking: https://facebook.github.io/relay/docs/en/thinking-in-relay.html

Hope it helps :)

Foley answered 1/11, 2018 at 21:15 Comment(1)
Thanks, the article you linked gave a very good reason in favor of fragments (:Lishalishe
L
5

This is the answer from my co-worker Jan Kassens who works on the Relay team:

If splitting out components makes sense to you, you should go for it. I find smaller modules generally help making code more understandable. Now, a Button component probably doesn't have to have a fragment attached to it, but if it's a "Like Page" button with a mutation and maybe label specific to the page, I think it makes total sense to make that it's own fragment container.

As with so many things in engineering, there's probably trade offs in splitting out too much, but we've spent a lot of thought on making fragment containers as lightweight and efficient as we can so you shouldn't think too hard about introducing overhead.

Lishalishe answered 1/11, 2018 at 23:27 Comment(1)
Very nice! Thanks for sharing that as well :)Foley
F
4

Yes, it is. Instead of querying all the data on root component and pass to others as props, you should create fragment containers and each of this component query its own data. And due to relay data masking, these data from fragments can only be seen inside the component that required it.

Maybe this is a good reading: https://medium.com/entria/relay-apollo-anti-pattern-d9f4dea47738

And this on Data Masking: https://facebook.github.io/relay/docs/en/thinking-in-relay.html

Hope it helps :)

Foley answered 1/11, 2018 at 21:15 Comment(1)
Thanks, the article you linked gave a very good reason in favor of fragments (:Lishalishe

© 2022 - 2024 — McMap. All rights reserved.