I’m using NextJS14 with the app router.
I want to create a game project.
Initially, a description of the game and a Start button are displayed. When the Start button is clicked, the description disappears and the game begins.
"use client";
import { useState } from "react";
import Game from "./Game";
export default function StartButton() {
const [start, setStart] = useState(false);
return (
<>
{!start && (
<button
onClick={() => {
setStart(true);
}}
>
Start
</button>
)}
{start && <Game {...props} />}
</>
);
}
I would like the game description to be implemented using Server-Side Rendering (SSR) to enhance SEO. However, due to the need to handle the Start button click event, I am currently using useState.
However, implementing the code as described will result in all of it being rendered client-side (CSR).
How can I resolve the issue described above?
Thank you in advance for your help.
2
Answers
Your component is still rendered by the server with whatever the default values for the
useState
are, it’s not entirely client-side rendered. The server is able to pre-render this component with its default values for SEO, only the dynamism is left out.Your current component tree can be generated to the following HTML:
With that said, typically with Next.js you’ll want to organize your component tree in such a way that you minimize the use of
'use client'
whenever you can, while maintaining your components as modular as possible.In your particular case, I’d recommend you think about your
StartButton
component since it’s not really just as a "start" button, it’s also handling the game rendering logic.While it doesn’t look too bad right now, it is better to have components do one thing and one thing well so any future changes do not hit you hard.
To make the description be implemented using SSR, you can create a server-rendered component :
and call it inside your Game component :
Start button component is fine and would work unchanged.