Alex Foxleigh
Alex Foxleigh

Reputation: 1964

A large query on the parent component or a series of small queries on each children?

Hopefully self-explanatory. I'm building a React/Apollo app and I want to ensure I'm using best practice.

Is it better to do a single, large query on the parent app that gets everything the children need (which is then passed via props/state) or just pass the params to the child components and have each child component execute it's own smaller query?

Upvotes: 2

Views: 461

Answers (1)

GG.
GG.

Reputation: 21864

Depends if you need to render all the children at the initialisation of your app.

Example 1:

parent -- page A (data 1) -> visible at initialisation
       -- page B (data 2) -> not visible at initialisation
       -- page C (data 3) -> not visible at initialisation

In this case, fetch only the data for page A (in page A).

Example 2:

parent -- element A (data 1) -> visible at initialisation
       -- element B (data 2) -> visible at initialisation
       -- element C (data 3) -> visible at initialisation

In this case, fetch everything (in the parent).

If you need to fetch everything, it's better to have a single large request. Just be sure the backend of your application can handle it properly with good performance. Sometimes it can be better to make a first simple request to start displaying something to your users, and make a second request for something harder to compute in the backend.

Also, a general rule: benchmark your solutions, compare the results and choose the best one.

Upvotes: 2

Related Questions