Search code examples
relayjsrelay

Why do we need a root query?


QueryRenderer takes a “query” prop, which contains a topmost query of the application made of fragments for downstream components:

const LinkListPage = () => (<QueryRenderer
  query={ rootQuery }
  { ...otherProps }
  render={
    (error, props) =>
      <LinkList viewer={ props.viewer } />
  }
/>)

/* ... */

const rootQuery = graphql`
  query LinkListPageQuery {
    viewer {
      ...LinkList_viewer
    }
  }
`

In the above example, the fragment “LinkList_viewer” is self-sufficient, and it tells us which container it supplies data to, and which prop it fills in.

Why the relay compiler does not assemble that root query on its own? Why do we need to repeat the typing of props.viewer, when it's immediately obvious and unambiguous what to pass where? Is there any case when manual construction of the root query helps us?


Solution

  • The root query is used to distinguish asking for data that is idempotent (query) from asking for data that will mutate the state (mutations) from data the behaves in other ways (subscriptions).

    I think the philosophy in the Relay library is to not try and have too much magic in the implementation of using it, hence that lack of automatically passing the data in a query with only one node.