r/reactjs • u/Dazzling_Chipmunk_24 • Jul 02 '26
Needs Help Best Method to Call Apis on Page load
I have an app that calls 3 different APIs on page load, where each call depends on the previous one succeeding — API 2 only fires after API 1 returns successfully, and API 3 only fires after API 2 returns successfully.
I'm considering three approaches: a useEffect with an empty dependency array, TanStack Query, or SWR.
Would TanStack Query with the enabled option be the best approach here, or does anyone have a better recommendation?
5
Upvotes
10
u/Glum_Cheesecake9859 Jul 02 '26
Yes TanStack Query with enabled is best.
Alternatively just as async TanStack query manually triggered with refetch would work, so you could probably do
await fetchA();
await fetchB();
await fetchC();
25
u/maqisha Jul 02 '26
Obviously, something thats industry standard like tanstack query will be one of the better approaches, and certainly better than you trying to roll this on your own.
However, having to make 3 different api calls that all depend on the previous one sounds like a serious mess on your backend. I would focus on figuring this out much more than a way to make these waterfall requests in React.
2
u/octocode Jul 02 '26
do all three need to complete before you have content to render on the page?
1
u/anonyuser415 Jul 02 '26
That's what I do 👍
Make sure to really watch your caching times for the dependent queries to avoid a stampede
And consider looking into ways to prefetch API 1 if you can, even before React mounts!
1
u/adfawf3f3f32a Jul 02 '26
what router are you using? i'm a fan of using loaders & tanstack query's ensureQueryData
2
u/everyoneisadj Jul 02 '26
Tanstack query using the enabled option.
Rule of thumb, use effects should be a last resort. It’s the quickest way people get into an anti pattern and rendering hell.
That doesn’t mean they aren’t used under the hood in a tool like tanstack, but their use is tried and true.
1
u/HauntingArugula3777 Jul 02 '26
Tanstack before/load really is quite nice
1
u/PapajG Jul 02 '26
Just treat each load in its own layer, deal with one and it’s success and failure in each layer, if you want to do all three at the same time, make a hook which returns what you need and loading state. Dont overcomplicate it
1
u/MarionberrySea5797 Jul 02 '26 edited Jul 25 '26
If you can fix on the backend so you only have to make 1 API call you should do that. If that's not possible you can use the BFF (Backend For Frontend) pattern to orchestrate calling all 3 different APIs, then all your frontend has to do is call your single BFF API.
1
u/Mindless-Arrival-106 Jul 02 '26
People love debating useEffect vs TanStack Query.
Meanwhile the app is sitting there making three blocking requests in a row.
That's the part I'd lose sleep over.