Remember the good old days when you could just use a UseEffect() hook, define an async function with useCallback() and call it inside useEffect(), use an AbortController() to abort the fetch when the component unmounts, use useState() to make the isLoading and isError states and manage them inside your try-catch, and call it a week?
Nowadays there are more ways to fetch your data and display it inside your component.
1. Fetching on the Client
Before the introduction of Server Components and Server Actions, all data fetching had to be done on the client. If you needed to hide sensitive information like API keys, you had to have another API between the client and the final API endpoint that fetched the data using the API key and sent it to the client.
1-1. useEffect() + useState()
This is the old way of doing it described at the start. the downside is that you have to write everything yourself (you have to add caching and re-fetching on top of everything mentioned already).
1-2. Data Fetching Libraries
There are libraries like SWR, RTK Query, and React Query that simplify the data fetching process on the client and take care of the state, error handling, caching, and re-fetching for you.
2. Fetching on the server
Server Components and Server Actions allow data fetching and processing to be run on the server. The final result is sent to the client for display hiding all sensitive information and allowing for server caching of the data. This is the new paradigm in the React ecosystem.
2-1. Server Components
Server Components run on the server and unlike client components, can by async and directly (without the need for useEffect()) await and fetch the data and send the final result to the client. on top of the previously mentioned advantages of fetching on the server, this allows for patterns like Partial Prerendering where part of the page can be static and only the server components that need to fetch the data can be dynamically streamed.
2-2. Server Actions
Server Actions are functions that run on the server and can be used to fetch data or perform any other task. The main benefit of Server Actions is that they can be called from client components. This gives you fine-grain control to choose which part of your code you want to run only on the server.
Because RSC (React Sever Components) and Server Actions are a new addition, there are some compatibility issues with some packages and libraries but they are getting updated and new workarounds are being implemented as we move forward.