Search code examples
reactjsgraphqlrelayjsrelay

What is benefit of relay graphql fragment?


I have months of experience of using relay graphql. I continue the project from another dev that is leaving, I use one QueryRenderer on every page and pour the data fetched from the main query as a plain object as props to every child component, I see no problem here. But I see people are using fragments and suggesting fragments heavily. I think it's just more typings and real waste. I don't really understand, we can just put the data as a prop to every child component, so why people really need a fragment? is there a technical benefit that I miss?


Solution

  • It helps you to maintain your code.

    If you have a Page with 3 different components and every component need different data than you can specify the needed data for each component within a fragment inside the component. If you later want to get rid of one of the 3 components, you just need to remove the fragment for this component form your QueryRenderer instead of checking which params you can remove from your QueryRenderer.

    By specifying the needed data in the component it is much easier to be sure to have the correct and only the necessary data fetched. If 3 different developers write the components (each of them one), it is easy to write the QueryRenderer for the page. Because instead of checking the data each component needs and passing the individual params to the components, you just specify the 3 fragments in the QueryRenderer and it will work.