Escaga Seen
Escaga Seen

Reputation: 151

Hybrid render with Next.js?

I'm new to Next.js and I'm using it to perform server side rendering on the landing page.

The landing page has: 1 generic component that's the same to every user and 1 component that is specific for each user.

Is it possible to perform server side rendering on the generic component, and client side rendering on the specific one?

Thank you.

Upvotes: 0

Views: 2442

Answers (2)

developper-ta
developper-ta

Reputation: 31

To make a page both dynamic and static at the same time is possible. the solution for dynamic: you have to use react useState then useEffect to send the request after unloading fishing on the client side but first must use next.js api getStaticProps() make the page static user's first visit

Upvotes: 0

Erv Walter
Erv Walter

Reputation: 13788

Yes, you can do client-rendering for any component in your hierarchy. Client rendering usually means that when the component first renders, it fires off some asynchronous request for data (from an API, etc).

In your SSR page, just have your user-specific component not render anything on the initial render (except maybe some loading UI). Then include a useEffect hook that triggers the API call and sets state (local or global state as appropriate) which will trigger your component to re-render with the user-specific data.

During SSR, only the loading state will render. As soon as the component is mounted, the useEffect will trigger and the user-specific data will load and the component will re-render.

Overly simplistic example:

const UserGreeting = () => {
  const [name, setName] = setState();

  useEffect(() => {
    getUserNameAsync().then((data) => {
      setName(data.name);
    })
  }, [setName])

  if (!name) {
    return <div>...</div>
  }

  return (
    <div>Welcome, {name}</div>
  )
}

Upvotes: 3

Related Questions