Reputation: 13
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="ko-KR">
<link rel="icon" href="/favicon.ico" sizes="any" />
<body>
<ThemeProvider>
<Topbar />
<div className={styles.mainContentContainer}>
<main className={styles.mainContent}>
{children}
<Footer />
</main>
</div>
<BottomBar />
</ThemeProvider>
</body>
</html>
);
}
/** ThemeProvider.tsx */
"use client";
import { darkTheme, ligthTheme } from "@/app/styles/themes/theme.css";
import "../../globals.css";
import { themeContainer } from "./ThemeProvider.css";
import { useEffect, useState } from "react";
import themeStore from "@/app/store/themeStore";
const ThemeProvider = ({ children }: any) => {
const { isDark } = themeStore();
const [theme, setTheme] = useState<string | null>("");
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
if (mounted) {
document.body.style.backgroundColor =
theme === "dark" ? "rgb(16,16,16)" : "rgb(245,245,245";
}
}, [theme, mounted]);
useEffect(() => {
setTheme(localStorage.getItem("theme"));
}, [isDark]);
if (!mounted) return null;
return (
<div className={` ${theme === "dark" ? darkTheme : ligthTheme}`}>
<div className={themeContainer}>{children}</div>
</div>
);
};
export default ThemeProvider;
I used LocalStoarge to save the theme.
And made a new component and wrapped children up on RootLayout.
As far as I know, if the upper component is the client component, the lower component is also the client component.
However, if in this code, I could use the server component internally.(e.g. cookie, "use server"
...)
I want to understand the difference between placing components inside ThemeProvider tags and inside the ThemeProvider.tsx file itself.
In the latter case, the internal component cannot use the server component.
Upvotes: 0
Views: 46
Reputation: 853
In NextJS components are either rendered on the server or in the client (browser).
Adding 'use client'
forces the component to be rendered on the client, giving you access to things such as local storage. However children of that component are still rendered on the server and passed as HTML, so they don't have access to (for example) local storage.
For each component you write, you have to choose where it should, with associated benefits and drawbacks.
Upvotes: 0