useQuery hook, client side cache best practices in React Apollo

Viewed 88

Let’s say we have a component tree in react

<Tree>
    <TreeTrunkDetails/>
    <TreeLeavesDetails/>
</Tree>

and a useTree hook that wraps a useQuery hook that fetches something like

tree {
  specie
  genus
  leaves {
    shape
    size
  }
  trunk {
    bark
    diameter
  }
}

We could call useTree in <Tree> and then pass trunk and leaves data to

<TreeLeavesDetails details={leaves}/>

and

<TreeTrunkDetails details={trunk}/>

respectively.

We could also hook <Tree> and <TreeLeavesDetails/> and <TreeTrunkDetails/> with the same useTree hook. Given that results will be cached in the client (assuming we can cache) the performance will be ok

Or we could create a useTree, useTreeTrunk and a useTreeLeaves hooks and the hook each component with its specific hook (and query requesting only the data it needs).

What are the pros and cons of each approach? Is there a recommended pattern from the Apollo team? Thank you

1 Answers

In the trivial case, it's fine to useQuery in each component. In the extreme case, you do add additional overhead per useQuery invocation. Each instance sets up a watch, which, when the cache updates needs to be evaluated.

If you think you're going to have a lot of Tree components on the page, it's best to issue one useQuery for each and pass data downwards.

Related