๐ฅ๐ฒ๐ฎ๐ฐ๐ ๐๐๐ฒ ๐๐ผ๐ผ๐ธ ๐ถ๐ป ๐๐น๐ถ๐ฒ๐ป๐ ๐๐ผ๐บ๐ฝ๐ผ๐ป๐ฒ๐ป๐๐
You want to fetch data in a Client Component. You do not need a big library.
Follow these steps:
- Start the fetch in an event handler.
- Save the promise in your state.
- Pass the promise to a child component.
- Use the use hook to read the data.
- Wrap the child in Suspense.
This is fast. The fetch starts when the user clicks.
Use a simple Map to cache your promises. This keeps the promise identity stable. It works the same way in Server Components and click handlers.
When do you need TanStack Query or SWR?
- You need to update data in multiple places.
- Data needs to refetch when you return to the tab.
- You need infinite scroll.
- You want optimistic UI.
If you do not need those, use the use hook. It is a simpler choice. Add a library later if your needs grow. The logic stays the same: promise in, data out, Suspense handles the wait.
Source: https://dev.to/kkr0423/reactjs-use-hook-in-a-client-component-38hi