Server Component
A concept in React that allow serverside rendering in a component level:
As a result we can have some components that are rendered staticly server. And some components that are rendered through client.
Their Next.js engine was designed in a way that automatically support us to do this out of the box.
Read: Making Sense of React Server Components (joshwcomeau.com)
Basically in the new react version, server component is by default. To use client component, we need to specify 'use client'
on top of the react file.
[!important]
In server component, the props of the component won't change. So it's like a static component. And hence, you cannot useuseEffect
useState
…
And client components cannot import server component. But server components can import other client components.
A way to think of this is to create a boundaries for those that's client component.
useState
and useEffect
in server component hack
If you find yourself need to do useState
and useEffect
in the server component, you can wrap it with a client component inside the code. For example:
import Header from './Header';
import MainContent from './MainContent';
import ColorProvider from './ColorProvider';
function Homepage() {
return (
<ColorProvider>
<Header />
<MainContent />
</ColorProvider>
);
}
The Homepage
here is a server component, Header
and MainContent
is also server components however ColorProvider
is a client component.
'use client';
import { DARK_COLORS, LIGHT_COLORS } from '@/constants.js';
function ColorProvider({ children }) {
const [colorTheme, setColorTheme] = React.useState('light');
const colorVariables = colorTheme === 'light'
? LIGHT_COLORS
: DARK_COLORS;
return (
<body style={colorVariables}>
{children}
</body>
);
}
Therefore you can useState
and stuff here.