Tips for rendering a server-side component within a client-side component in a React 18 - Next.js 14 application router

As outlined in this RFC:

Server Components or call server hooks/utilities cannot be imported by Client Components, as they are specific to server functionality.


Currently, I am developing a project using react v18.2 and nextjs v14 with app router integration.

The page I am currently working on is focused primarily on client-side features:

https://i.stack.imgur.com/ctR6M.png

This page serves as a client component due to its reliance on various client-side functionalities for form interactions utilizing the React useState() hook.

Below is an excerpt of the actual code from the page.tsx file, showcasing a sizable component that utilizes the JoyUI components library (built on MUI).

  • Key attention should be given to the very first line of the code where I have employed the "use client" directive, indicating that this component (NewModeratorPage) heavily relies on client-side features.

  • Another crucial aspect to note is the use of the <SelectCompany /> component within the return block of the <NewModeratorPage /> component:

'use client'

import React from 'react'
// Components imports

const NewModeratorPage = () => {
  // Component logic
  
}

export default NewModeratorPage

  • <SelectCompany /> functions as a server component, rendering a <Select> element populated with options fetched from an external API.

Hence, the <SelectCompany /> component is involved in data fetching operations, suggesting that it is better suited as a server component.

  • Upon user request, the page is delivered with the pre-fetched form and <SelectCompany/> content, eliminating any loading delays related to client-side data retrieval.

To indicate that this component is a server component, the "use server" directive is used.

Here's an overview of the <SelectCompany /> server component code snippet:

"use server"

import React, { PropsWithChildren } from 'react'
// Component imports

const SelectCompany = async ({ children, ...props }: SelectCompanyProps) => {
  // Data fetching operation
  
}

export default SelectCompany

I encountered the following browser error:

Error: async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server.

In addition, in my Linux terminal, I received the following error message:

Internal error: Error: Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead.

The root cause of these errors appears to be the restriction on client components importing server components,

So what is the solution to my case? I want <SelectCompanies /> to function as a server component.

Answer â„–1

In the documentation of Next.js, there are both supported and unsupported patterns discussed.

Unsupported Approach:

'use client'
 
// You cannot import a Server Component into a Client Component.
import ServerComponent from './Server-Component'
 
export default function ClientComponent({
  children,
}: {
  children: React.ReactNode
}) {
  const [count, setCount] = useState(0)
 
  return (
    <>
      <button onClick={() => setCount(count + 1)}>{count}</button>
 
      <ServerComponent />
    </>
  )
}

An alternative approach would be to pass the server component as a child element like this:

Supported Approach:

'use client'
 
import { useState } from 'react'
 
export default function ClientComponent({
  children,
}: {
  children: React.ReactNode
}) {
  const [count, setCount] = useState(0)
 
  return (
    <>
      <button onClick={() => setCount(count + 1)}>{count}</button>
      {children}
    </>
  )
}
// This pattern works:
// You can pass a Server Component as a child or prop of a
// Client Component.
import ClientComponent from './client-component'
import ServerComponent from './server-component'
 
// Pages in Next.js are Server Components by default
export default function Page() {
  return (
    <ClientComponent>
      <ServerComponent />
    </ClientComponent>
  )
}

By including them as children, we have full visibility of all server components and can effectively render or stream them.

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

"Disabling checkbox selection for DataGrid cells/fields in React Material UI - A Step-by-Step

Hello, I've encountered an issue with a checkbox selection and a link within the same cell in a Material UI DataGrid table. The challenge is that when clicking on a cell that contains an external link which redirects to another page, the checkbox a ...

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

Updating nested data in Prisma - a comprehensive guide

Let's take a quick look at the technologies in use before we dive deeper: Next.Js(app router) version 14.2.2 React version 18 prisma version 5.12.1 database -> mongodb Prisma is a new tool for me and I'm encountering issues while trying to u ...

React-hook-form being problematic: Radio button passing null value when selecting female option

Upon submission, I am encountering an issue where the value being retrieved is from the first option, resulting in a null value when selecting "female". However, the onChange function works correctly. <form onSubmit={handleSubmit(onSubmit)}> ...

Tips for resolving the npm ResourceUnavailable issue

Hey there! I'm currently experimenting with React. In my folder, I've got nodejs along with npm and npx files installed. While debugging, I've deleted and reinstalled this folder multiple times. However, no matter what directory or command I ...

Can I fetch the visible rows (along with their order) from a React Material-table?

I've recently started working with React and I'm utilizing a special component known for its unique filtering functionality that I couldn't find elsewhere. This component typically shows 10 rows of data by default. Whenever I apply filters ...

Is it possible to access Next.js API endpoints from another application?

Currently working on building a web application with React on the Next.js framework. I've established an API route that the web app's components retrieve data from. Now, I'm considering developing a mobile app as well - can I utilize the sam ...

Guide: Implementing material-ui theme with redux in gatsby

I'm currently utilizing the material-ui theme in conjunction with redux-toolkit within a gatsby project. This is my theme.ts file: import { createMuiTheme } from "@material-ui/core"; import { useSelector } from "react-redux"; import { State } from ". ...

Is it possible for Angular's `HttpClient` to use complex property types in the `.get()` generics aside from just `string` or `number`?

After spending an entire day researching the topic, I've hit a dead end. All my efforts have only led me to discover one thing—omission. None of the information I've come across mentions whether you can utilize non-simple types (such as string ...

During the prerendering process of the /write page in Next.js, a ReferenceError is thrown stating that the

Currently, I am in the process of developing an open-source blogging platform using Next.js. However, I have encountered a frustrating error while deploying the project. The issue arises when attempting to prerender the /write page, resulting in the follow ...

The dynamic duo of NextJS and react-query

https://i.stack.imgur.com/SPvy9.png Looking at the code snippet, it seems that I have employed useQuery() but need it to fetch data only once. Unsure whether this issue lies with NextJS or react-query. ...

I am facing difficulties in adding dynamic content to my JSON file

I've encountered a challenge in appending new dynamic data to a JSON file. In my project, I receive the projectName from an input form on the /new page. My API utilizes node.js's fs module to generate a new JSON file, where I can subsequently add ...

MUI CSS: Mastering image manipulation

My MUI React Component features a Card that contains an image and buttons <Card key={index} className="xl:w-[350px] w-[310px] max-h-[450px]"> <img src={meme.url} className="center bg-cover" alt="" /> <Box cl ...

The issue of focus being lost with HOC and Formik

In my latest project, I developed a bootstrap form input component that utilizes HOC (Higher Order Component) to change an icon upon submission. The input validation is done through the Formik library. <InputUi placeholder="Enter your email" ...

Displaying an array value instead of a new value list in a React component

Situation - Initial number input in text field - 1 List of Items - 1 6 11 Upon removing 1 from the text field, the list becomes - New List Items - NaN NaN NaN Now, if you input 4 in the field. The updated List Items are - NaN NaN 4 9 14 Expected ...

Starting a React app within a Laravel project can be a seamless process when following

I am facing an issue with my Laravel and React project setup. When I try to run npm start, I encounter the error "npm ERR! missing script: start". The project runs successfully when I use the command npm run dev. Is there a way to only run the React projec ...

The upcoming developer manages to execute the program successfully, however, it continues to load indefinitely

Executing the command yarn dev consistently runs successfully in my VS Code terminal: $ yarn dev yarn run v1.22.19 warning ..\..\..\..\package.json: No license field $ next dev ready - started server on 0.0.0.0:3000, url: http://localho ...

The npm postinstall script will only execute if no packages are currently being installed

I made a mistake The reason behind why running npm install whatever results in the deletion of the node_modules/- folder is not what I initially thought. I mistakenly believed it executed the preinstall script but skipped the postinstall script, which was ...

Error encountered while trying to install eslint-plugin-react with an incompatible engine

Hello, I am a new React user and I am running into an issue in my terminal after installing eslint-plugin-react and eslint-plugin-react-hooks. npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '@es-joy/<a href="/cdn-cgi/l/emai ...

Discovering the status of a wrapped component using Jest

const wrapper = mount( <ContextProvider> <FreeformEquationQuestionPractice question={question} /> </ContextProvider> ) console.log('freeform state: ', wrapper.childAt(0).instance().state) FreeformEquationQues ...