Which way of using apollo store is recommendable, read fragment/read query or connecting query using graphql hoc in component or passing the props?

Viewed 547

We are using react-apollo and it's graphql HOC in our project. Also, we are using PureComponent from react to ensure that every time the parent re-renders, it doesn't cause re-rendering of the child component if child's props aren't changed. And for reading and writing in apollo cache, we use apollo client.

The graphql HOC is hooked with a component to retrieve the data from server and it will store the data to the cache. And we want to provide some part of that data to the descendent component from cache.

Let's take an example. At an ancestor level, we fetch list of items from server. And at child level, we need detail of a particular item which is already there in apollo store.

For doing the same, there are three possible ways:

  1. Passing data as props to the descendent components.
  • Here is render method of Grand Parent Component where we fetch list of items from server.
render(){
  return (
    <ListComponent list={this.props.list}/>
  )
}
  • Here is render method of List Component.
render(){
  return (
    <ItemComponent list={this.props.list} selectedItem={"1"}/>
  )
}
  • Here is render method of Item Component.
render(){
  const item = this.props.list[this.props.selectedItem]
  return (
    <div>{this.props.item}</div>
  )
}
  1. To hook graphql HOC inside descendent component with fetch-policy set to cache-first.
  • Here is Item Component where we hook graphql query to get item.
class ItemComponent extends React.PureComponent {
 render(){
  return (
     <div>{this.props.item}</div>
  )
 }
}
export default compose(
 graphql(QUERY, {
 options: ({id}) => ({
    variables: {id}
  })
 }
)
  1. To use apollo client's readFragment function.
render(){
  const item = client.readFragment({
    id:`List:${this.props.selectedItem}`
    fragment:"ListFragment"
  });

  return (
    <div>{this.props.item}</div>
  )
}

Also there are related pros and cons with these three approaches.

  1. First approach works well in every cases. The only problem is we pass data top-down via unnecessarily props.

  2. Second approach works well in every cases. The only problem is we have to unnecessarily hook query to access cache.

  3. Third approach looks clean but the only problem is the component doesn't re-render when apollo cache is updated because we use PureComponent.

I am confused between these three approaches. So if you can provide an insight of which approach should I use or if you can provide any other hybrid approach then it would be a great help.

0 Answers
Related