𝗥𝗲𝗮𝗰𝘁 𝘂𝘀𝗲 𝗛𝗼𝗼𝗸 𝗶𝗻 𝗖𝗹𝗶𝗲𝗻𝘁 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀
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