Nov 07 2023
Waterfall vs. Parellel Data Fetching in React Server Components
With React Server Components, you can define and execute your data fetching function directly in the component itself:
const fetchData = async (endpoint: string) => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/${endpoint}`
);
return response.json();
};
const data = fetchData("cars");
When you need to make calls to different API endpoints inside the same component, you can use either execute your functions with either a waterfall (successive calls) or a parallel method (concurrent calls).
Waterfall Fetching
- The execution of one of your fetching functions depends on the data returned by another function
- Use await in both calls
const waterfall = async () => {
const user = await fetchData("users/1")
const userPorsts = await fetchData(`posts?userId=${user.id}`)
}
Parallel Fetching
- The data fetching functions can be executed independently from one another
- Group both calls inside a Promise.all
- Don't await each call, instead await the execution of the Promise.all
const parallel = async () => {
const usersData = fetchData("users")
const postsData = fetchData("posts")
const [users, posts] = await Promise.all([usersData, postsData])
}