Is it possible to render a placeholder to display while a client component loads?

I kinda wanted <suspense> to do this for me but it doesn't seem to. Let's say I have a client component (from a library) that is 100px when it renders. When I include that in my server component, the initial HTML payload just has an empty comment where it should be (<!-- -->), then when the client hydrates it pops in and suddenly what was previously 0px is now 100px. I'd like to be able to render a skeleton that disappears after the hydration, is this possible?
6 Replies
greypixel
greypixel9mo ago
Hm, kinda answered my own question here:
"use client";

import { useLayoutEffect, useState } from "react";

export function SomeClientComponent() {
const [isRendered, setIsRendered] = useState<boolean>(false);
useLayoutEffect(() => {
setIsRendered(true);
}, []);
return !isRendered ? (
<div className="h-10 w-[180px] rounded-sm bg-red-300">&nbsp;</div>
) : (
<SomeClientComponent />
);
}
"use client";

import { useLayoutEffect, useState } from "react";

export function SomeClientComponent() {
const [isRendered, setIsRendered] = useState<boolean>(false);
useLayoutEffect(() => {
setIsRendered(true);
}, []);
return !isRendered ? (
<div className="h-10 w-[180px] rounded-sm bg-red-300">&nbsp;</div>
) : (
<SomeClientComponent />
);
}
This seems to work pretty well, guess I'll make a component to wrap this behaviour
erik.gh
erik.gh9mo ago
not sure if i fully understand but can‘t you just use min-width?
greypixel
greypixel9mo ago
by default nothing is rendered at all so nothing to put min-width on and I don't have control over <SomeClientComponent />
erik.gh
erik.gh9mo ago
wrapping the component is not possible?
greypixel
greypixel9mo ago
I could wrap it in a min-width div sure but I wanted to render a block that disappears rather than just have component pop in I guess I can do a min-width min-height div with a background color
erik.gh
erik.gh9mo ago
when i run into problems like these i am normally able to resolve them by editing the layout "one layer up"
Want results from more Discord servers?
Add your server