react-infinite-scroll-hook icon indicating copy to clipboard operation
react-infinite-scroll-hook copied to clipboard

support for server components?

Open Nithur-M opened this issue 2 years ago • 1 comments

I am trying to use this package in nextjs app directory. But it fails because of calling client components from server files. Since the useLoadItems use useState it must be declared as client components. So it throws error when calling from page file.

Attempted to call useLoadItems() from the server but useLoadItems is on the client. 
It's not possible to invoke a client function from the server, it can only be rendered as a Component or 
passed to props of a Client Component.

Thanks.

Nithur-M avatar Mar 14 '23 10:03 Nithur-M

Hello there 👋

Besides client hooks like useState, this hook relies on IntersectionObserver under the hood and it works on browser/client-side.

So, as you should use client components to be able to handle user interactions etc., this hook should be used in a client component too, since it needs to interact with the browser/viewport.

There can be different approaches based on the requirements.

If you don't want to render any of the list items on the server, you can just make the whole list a client component and fetch all the pages on the client-side. But this approach can increase your initial page load time, so it might not be the best approach for some cases.

If you want to render the first page on the server, the most straightforward approach I can think of is:

  • Fetch the initial page on the server, by using a server component.
  • Render the list of items as a child of this server component. The list should be a client component. Pass the initial page as a prop to this component.
  • Since the list is a client component, you can use the infinite scroll hook here by creating a sentry.
  • Merge the initial page (fetched on the server) and following pages (fetched on the client) based on your data fetching strategy (swr, React Query, custom etc.).

A simple visualization is like this: image

And here is a simple demo: https://stackblitz.com/edit/nextjs-cucrhe

I will add this topic to the README and close this issue afterwards.

Thanks 🙏

onderonur avatar Mar 24 '23 00:03 onderonur