Help: Text content does not match server-rendered HTML.
Answered
Singapura posted this in #help-forum
SingapuraOP
I make a random number generator, and i wanted it to only work on the client side. so i added the 'use client' declaration on the first line. but the error is shown.
'use client'
import {create} from 'zustand'
import {nanoid} from "nanoid";
interface BearState {
bears: string
}
const useBearStore = create<BearState>()((set) => ({
bears: nanoid(),
}))
export function _Chat() {
const bearStore = useBearStore();
console.log("------", bearStore.bears)
return (
<div>
{bearStore.bears}
</div>
)
}
export default function Home() {
return (
<div>
<_Chat/>
</div>
)
}
Answered by Singapura
'use client'
import {create} from 'zustand'
import {nanoid} from "nanoid";
import {NoSSR} from "next/dist/shared/lib/lazy-dynamic/dynamic-no-ssr";
import {Suspense} from "react";
interface BearState {
bears: string
}
const useBearStore = create<BearState>()((set) => ({
bears: nanoid(),
}))
export function _Chat() {
let bearStore = useBearStore();
console.log(bearStore.bears)
return (
<div>
{bearStore.bears}
</div>
)
}
export default function Home() {
return (
<div>
<Suspense fallback={<div>Oop, any error</div>}>
<NoSSR>
<_Chat/>
</NoSSR>
</Suspense>
</div>
)
}
4 Replies
Because client component will be rendered on server first and send it to client. If you want to work on client only, you could use
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#skipping-ssr
dynamic
with ssr: disable
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#skipping-ssr
SingapuraOP
Thank you, I found two ways to solve it.
SingapuraOP
'use client'
import {create} from 'zustand'
import {nanoid} from "nanoid";
import {NoSSR} from "next/dist/shared/lib/lazy-dynamic/dynamic-no-ssr";
import {Suspense} from "react";
interface BearState {
bears: string
}
const useBearStore = create<BearState>()((set) => ({
bears: nanoid(),
}))
export function _Chat() {
let bearStore = useBearStore();
console.log(bearStore.bears)
return (
<div>
{bearStore.bears}
</div>
)
}
export default function Home() {
return (
<div>
<Suspense fallback={<div>Oop, any error</div>}>
<NoSSR>
<_Chat/>
</NoSSR>
</Suspense>
</div>
)
}
Answer
SingapuraOP
'use client'
import {create} from 'zustand'
import {nanoid} from "nanoid";
import dynamic from "next/dynamic";
interface BearState {
bears: string
}
const useBearStore = create<BearState>()((set) => ({
bears: nanoid(),
}))
export function _Chat() {
let bearStore = useBearStore();
console.log(bearStore.bears)
return (
<div>
{bearStore.bears}
</div>
)
}
const Chat = dynamic(async () => (await import("@/app/page"))._Chat, {ssr: false});
export default function Home() {
return (
<div>
<Chat/>
</div>
)
}