Can you explain the distinction between the server component and client component in Nextjs 14?

export default function CustomLayout({
  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 saved the selected theme in LocalStorage.

Incorporated a new component and placed children within RootLayout.

Based on my understanding, when the above component is considered client-side, so is the subsequent one.

However, in this scenario, I was able to utilize server components internally (e.g. cookie, "use server"...).

I aim to grasp the distinction between including components within ThemeProvider tags versus inside the ThemeProvider.tsx file itself.

With the latter case, internal components are unable to use server-side components.

Answer №1

When working with NextJS, components can be rendered either on the server or in the client (browser).

If you include 'use client' in a component, it will be specifically rendered on the client side, allowing access to features like local storage. However, keep in mind that any children of that component will still be rendered on the server and passed as HTML, meaning they won't have access to resources like local storage.

With each component you create, you must decide where it should be rendered and consider the advantages and disadvantages of each option.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create personalized access tokens through Azure Active Directory (AD)

Currently, I am working on a Next.js application that requires users to log in using their Azure ID. Once logged in, I need to verify the email and other details from the token on my Node.js backend before sending a custom token to the frontend for addit ...

Having trouble incorporating a title in the header section

I encountered an issue while attempting to include the Fragment, title, and Head. When these are added, an error occurs but when removed, the page displays correctly. I have searched for a solution to this problem but couldn't find anything. import ...

How can I change the background color of a selected row in material-table?

I am looking to achieve a similar behavior as demonstrated in this example using the material-table library: https://codesandbox.io/s/table-hover-colors-zw9nt If you are interested in learning more about the material-table library, you can visit these li ...

The Google analytics script encountered issues loading on a page, resulting in a 500 error code

Encountering a persistent issue where the Google Analytics script fails to load with a 500 error code on the website, but interestingly works fine when opened in a new tab. After testing on MacOS BigSur using Chrome, Firefox, and Safari in both normal and ...

receiving incorrect request rather than the complete error message

Handling errors when using POST with the same user email can be achieved using the following code snippet (utilizing superagent): export function signUpUser(userData) { return async dispatch => { try { const currentUser = await request.pos ...

React Native: Encounter Unexpected Token Transform Error (

Yesterday, I successfully followed the instructions on React Native's Android Setup Page and ran the code without any issues. However, today when I attempted to run the same code, it displayed a "build is successful" message but only showed a android/ ...

Customizing the context-path of the React app, achieve Sprig Boot and React bundling as a WebJar

I have developed a Spring Boot backend application integrated with a React frontend (BFF). I followed the standard spring boot setup from spring initialiser and utilized create-react-app to generate the frontend. Everything is working smoothly so far. To b ...

Encountering npm installation errors with react-messenger-customer-chat

Is anyone facing issues with the installation of react-messenger-customer-chat? [Next.js, tailwind] Check out the GitHub repository here: https://github.com/Yoctol/react-messenger-customer-chat package.json { "name": "with-tailwindcss&quo ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

What is the process for adjusting the color of the underline in Material UI input fields

I am facing an issue with a Material UI Select component that is on a dark background. I want to change the text and line colors to white just for this particular component, while keeping the rest of the Select instances unchanged. Although I have managed ...

Guidelines on switching from Create React App 5.0.0 to version 4.0.3

I've encountered an issue with create-react-app where the latest release requires Node 14, but my workplace only approves version 12.16.3. In this scenario, I'm exploring ways to use create-react-app with an older version of Node. I attempted to ...

The nested grid containers and items are overflowing off the screen when using material UI react

I am attempting to create a user interface similar to the one shown below, but I am facing some difficulties in achieving the desired outcome. I have experimented with adjusting the columns as well, but that didn't yield the expected results either. ...

Error: Docker is experiencing a permission issue with creating the directory '/app/node_modules/.cache'

I came across a permission error while attempting to create a docker container within a React application. I tried looking at various community responses, but none of them seemed to work. After going through a related discussion, I attempted the foll ...

Loading dynamic fonts in React MaterialUI

In our web application, each user experiences a unique style with colors, fonts, border widths, and more based on the Material UI JSON theme retrieved from the database upon loading the app. The challenge lies in handling dynamic fonts. What approaches ha ...

Unable to find the Popper component in Material UI

Material-UI version "@material-ui/core": "^3.7.0" I have a requirement to display Popper on hover over an element, but unfortunately, the Popper is not visible. This section serves as a container for the Popper component. import PropTypes from &apos ...

What is the best method to retrieve the transloadit final link stored on a file's storage server (such as Google Cloud Storage) and bring it back to the component?

Trying to understand how to retrieve the final link stored in Google Storage (starting with "https://storage.googleapis.com/...") within a React component, but finding the documentation unclear. Even after successful file upload, I keep receiving "ASSEMBL ...

Displaying a TypeScript-enabled antd tree component in a React application does not show any information

I attempted to convert the Tree example from antd to utilize TypeScript, however, the child-render function does not seem to return anything. The commented row renders when I remove the comment. The RenderTreeNodes function is executed for each element in ...

Access is restricted by Firebase when attempting to utilize the env file

I am in the process of developing a react-app that integrates with Firebase. The typical setup for credentials is as follows: const firebaseConfig = { apiKey: ..., authDomain: ..., projectId: ..., storageBucket: ..., messagingSenderId: ...

Ways to create genuine routes in a fixed NextJS site with properly functioning image pathways

Trying to deploy a static NextJS website involves exporting a distribution folder and uploading it to the server. An issue arises when clicking on a link to another path, such as '/about', which works fine. However, if the page is reloaded or th ...

Wrapper class for iOS and Android libraries in React-Native

Currently, I am exploring React Native and aiming to develop a unified interface (wrapper) for two libraries with similar functionalities but tailored for different platforms. For instance, DatePickerIOS & react-native-wheel-picker-android. I've expe ...