<Query> vs graphql Hoc which is best way to hook graphql query with component in react apollo

Viewed 817

React Apollo 2.1 introduce <Query/> component to hook graphql query with component.

<Query query={GET_DOGS}>
{({ loading, error, data }) => {
  if (loading) return "Loading...";
  if (error) return `Error! ${error.message}`;

  return (
    <select name="dog" onChange={onDogSelected}>
      {data.dogs.map(dog => (
        <option key={dog.id} value={dog.breed}>
          {dog.breed}
        </option>
      ))}
    </select>
  );
}}

In older version we use graphql Hoc to hook query.

export default compose(
  graphql(GET_DOGS)(MyComponent),
  withLoader
)(Component)

Here withLoader HOC handles loading, error and data state.

function withLoader(WrappedComponent) {
    class comp extends React.PureComponent {
       render(){
          return this.props.isData?<WrappedComponent {...this.props}/>:<Loading/>
       }
    }
}

So which is best way to hook query and why? Is it wise decision to shift all queries which was written using graphql HOC into latest <Query/> component.

I'm not getting any pros writing a query according Apollo 2.1 . Personally writing a query using hoc looks clean and decoupled. But some people doesn't recommended use hoc.

1 Answers

IMHO <Query/> components were introduced only to simplify the initial barrier for newcomers. They look like other components and are easy to read.

Their use is limited to simple use cases - using them quickly becomes complicated in more complex scenarios.

Try to use data from <Query/> in other life cycle or try to use a few of them (<Mutation/>) in one render.

You'll quickly be back in composing HOCs ;)

Related