Best practice in React regarding parent and children using the same hook to fetch data, passing the data down via props, or specific hooks

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 pattern is recommended by the Apollo team?
Thank you

2 Likes

It’s a good question. Personally I’m finding performance issues when I’m using too many instances of useQuery (in the 100s or 1000s).

I haven’t found a great way to improve the performance here other than to use less useQuerys and use more contexts/props.

There’s a new hook coming in v3.7 called useFragment which may make this easier: Feature: useFragment hook · Issue #8236 · apollographql/apollo-client · GitHub