sonner icon indicating copy to clipboard operation
sonner copied to clipboard

Rendering message on React Server Component page load

Open ScreamZ opened this issue 2 months ago • 5 comments

I would like your insight on a use case,

I'm using NextJS with RSC and I would like to display a message to a user arriving on the website only if it is logged.

Currently I ended up with this pattern, but sadly I have to render null, is there any way to proceed ? I used such pattern when hooks where not existing, but now we are supposed to use hooks, but using a custom hook with use client doesn't seems to work.

"use client";
import { Session } from "next-auth";
import { useEffect, useRef } from "react";
import { toast } from "sonner";

type HelloBannerProps = {
  session: Session | null;
};

export function HelloBanner({ session }: HelloBannerProps) {
  const isHandled = useRef(false);

  useEffect(() => {
    const userName = session?.user?.name;

    if (userName && !isHandled.current) {
      isHandled.current = true;
      requestAnimationFrame(() => toast(`Welcome back to the ${userName}!`));
    }
  }, [session]);

  return null;
}

Thanks

EDIT:

Humm, it seems complicated with server components when the URL change useEffect is played again. Not sure how to deal with my use case now

I guess this is a use case for a full client mode? But how? Was easier with page router 😅

https://github.com/emilkowalski/sonner/assets/6640835/7fc34060-afc9-47d1-95a4-5984cb602394

ScreamZ avatar May 01 '24 16:05 ScreamZ