Giter Site home page Giter Site logo

reactjs / server-components-demo Goto Github PK

View Code? Open in Web Editor NEW
4.2K 4.2K 628.0 124 KB

Demo app of React Server Components.

Home Page: https://reactjs.org/server-components

License: MIT License

JavaScript 68.88% HTML 2.22% CSS 27.88% Dockerfile 0.38% Shell 0.64%

server-components-demo's Introduction

React Server Components Demo

What is this?

This is a demo app built with Server Components, an experimental React feature. We strongly recommend watching our talk introducing Server Components before exploring this demo. The talk includes a walkthrough of the demo code and highlights key points of how Server Components work and what features they provide.

Update (March 2023): This demo has been updated to match the latest conventions.

When will I be able to use this?

Server Components are an experimental feature and are not ready for adoption. For now, we recommend experimenting with Server Components via this demo app. Use this in your projects at your own risk.

Should I use this demo for benchmarks?

If you use this demo to compare React Server Components to the framework of your choice, keep this in mind:

  • This demo doesn’t have server rendering. Server Components are a separate (but complementary) technology from Server Rendering (SSR). Server Components let you run some of your components purely on the server. SSR, on the other hand, lets you generate HTML before any JavaScript loads. This demo only shows Server Components, and not SSR. Because it doesn't have SSR, the initial page load in this demo has a client-server network waterfall, and will be much slower than any SSR framework. However, Server Components are meant to be integrated together with SSR, and they will be in a future release.
  • This demo doesn’t have an efficient bundling strategy. When you use Server Components, a bundler plugin will automatically split the client JS bundle. However, the way it's currently being split is not necessarily optimal. We are investigating more efficient ways to split the bundles, but they are out of scope of this demo.
  • This demo doesn’t have partial refetching. Currently, when you click on different “notes”, the entire app shell is refetched from the server. However, that’s not ideal: for example, it’s unnecessary to refetch the sidebar content if all that changed is the inner content of the right pane. Partial refetching is an open area of research and we don’t yet know how exactly it will work.

This demo is provided “as is” to show the parts that are ready for experimentation. It is not intended to reflect the performance characteristics of a real app driven by a future stable release of Server Components.

Setup

You will need to have Node 18 LTS in order to run this demo. (If you use nvm, run nvm i before running npm install to install the recommended Node version.)

npm install --legacy-peer-deps
npm start

(Or npm run start:prod for a production build.)

Then open http://localhost:4000.

The app won't work until you set up the database, as described below.

Setup with Docker (optional)

You can also start dev build of the app by using docker-compose.

⚠️ This is completely optional, and is only for people who prefer Docker to global installs!

If you prefer Docker, make sure you have docker and docker-compose installed then run:

docker-compose up

Running seed script

1. Run containers in the detached mode

docker-compose up -d

2. Run seed script

docker-compose exec notes-app npm run seed

If you'd rather not use Docker, skip this section and continue below.

DB Setup

This demo uses Postgres. First, follow its installation link for your platform.

Alternatively, you can check out this fork which will let you run the demo app without needing a database. However, you won't be able to execute SQL queries (but fetch should still work). There is also another fork that uses Prisma with SQLite, so it doesn't require additional setup.

The below example will set up the database for this app, assuming that you have a UNIX-like platform:

Step 1. Create the Database

psql postgres

CREATE DATABASE notesapi;
CREATE ROLE notesadmin WITH LOGIN PASSWORD 'password';
ALTER ROLE notesadmin WITH SUPERUSER;
ALTER DATABASE notesapi OWNER TO notesadmin;
\q

Step 2. Connect to the Database

psql -d postgres -U notesadmin;

\c notesapi

DROP TABLE IF EXISTS notes;
CREATE TABLE notes (
  id SERIAL PRIMARY KEY,
  created_at TIMESTAMP NOT NULL,
  updated_at TIMESTAMP NOT NULL,
  title TEXT,
  body TEXT
);

\q

Step 3. Run the seed script

Finally, run npm run seed to populate some data.

And you're done!

Notes about this app

The demo is a note-taking app called React Notes. It consists of a few major parts:

  • It uses a Webpack plugin (not defined in this repo) that allows us to only include client components in build artifacts
  • An Express server that:
    • Serves API endpoints used in the app
    • Renders Server Components into a special format that we can read on the client
  • A React app containing Server and Client components used to build React Notes

This demo is built on top of our Webpack plugin, but this is not how we envision using Server Components when they are stable. They are intended to be used in a framework that supports server rendering — for example, in Next.js. This is an early demo -- the real integration will be developed in the coming months. Learn more in the announcement post.

Interesting things to try

  • Expand note(s) by hovering over the note in the sidebar, and clicking the expand/collapse toggle. Next, create or delete a note. What happens to the expanded notes?
  • Change a note's title while editing, and notice how editing an existing item animates in the sidebar. What happens if you edit a note in the middle of the list?
  • Search for any title. With the search text still in the search input, create a new note with a title matching the search text. What happens?
  • Search while on Slow 3G, observe the inline loading indicator.
  • Switch between two notes back and forth. Observe we don't send new responses next time we switch them again.
  • Uncomment the await fetch('http://localhost:4000/sleep/....') call in Note.js or NoteList.js to introduce an artificial delay and trigger Suspense.
    • If you only uncomment it in Note.js, you'll see the fallback every time you open a note.
    • If you only uncomment it in NoteList.js, you'll see the list fallback on first page load.
    • If you uncomment it in both, it won't be very interesting because we have nothing new to show until they both respond.
  • Add a new Server Component and place it above the search bar in App.js. Import db from db.js and use await db.query() from it to get the number of notes. Oberserve what happens when you add or delete a note.

You can watch a recorded walkthrough of all these demo points here with timestamps. (Note: this recording is slightly outdated because the repository has been updated to match the latest conventions.)

Built by (A-Z)

Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.

License

This demo is MIT licensed.

server-components-demo's People

Contributors

ahmadawais avatar anuraghazra avatar gaearon avatar gregbrimble avatar jonjaques avatar leohxj avatar luk-z avatar lukyth avatar matanbobi avatar micorix avatar midudev avatar mylesborins avatar poteto avatar ryo-manba avatar sam17896 avatar swyxio avatar zhigang1992 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

server-components-demo's Issues

It seems react-server command cannot found

[0] [nodemon] starting `node --conditions=react-server server`
[1] [nodemon] 2.0.6
[0] node: bad option: --conditions=react-server

I tried npm start but It seems react-server command cannot found.

npm lockfileVersion warning

This project's package-lock.json has "lockfileVersion": 2, which is generated from npm@7. It comes with nodejs >= 15.

So by using Node 14 LTS as suggested in the README, it'll give this warning while running npm install

npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion@1, but package-lock.json was generated for lockfileVersion@2. I'll try to do my best with it!

What do you think about either updating the README and Dockerfile to use Node 15, or update package-lock.json to have lockfileVersion: 1 instead? I prefer the first option personally. I can take care of either option if you think it's good.

Using react-fetch on client

It seems using react-fetch purely on the client side (with all react versions on 0.0.0-experimental-3310209d0) it doesn't match what you see on the server, I get promises that aren't unwrapped.

It has a .browser version but I don't see any example usage on client, so will just leave this open for further information on if this is intended to work.

Integrate SSR

Hi! I am interested in learning the appropriate strategy to use RSC in combination with SSR. Currently, I am attempting to hydrate the DOM with the result of the RSC, but I am encountering an error that mismatches the result. I am not sure if the strategy I am attempting is correct or not. Could you please provide some guidance? To illustrate the issue, I have created a demo project, which you can find here: https://github.com/sviridoff/rsc-webpack-swc-fastify-demo. As you can see, I have hardcoded the result of the RSC directly in the HTML file here: https://github.com/sviridoff/rsc-webpack-swc-fastify-demo/blob/main/public/page.html. Here is how I am attempting to hydrate it: https://github.com/sviridoff/rsc-webpack-swc-fastify-demo/blob/main/src/bootstrap.tsx#L15

Suggestion: renderReactTree performance improvement

In renderReactTree the following block of code is only required once at runtime:

 await waitForWebpack();
 const manifest = readFileSync(
    path.resolve(__dirname, '../build/react-client-manifest.json'),
    'utf8'
 );
 const moduleMap = JSON.parse(manifest);

In the current example, the performance impact is minor but with a large number of components, doing this treatment for each server request can have bigger impact.

A quick optimization below:

let moduleMap;

async function renderReactTree(res, props) {
  if (!moduleMap) {
    await waitForWebpack()
    const manifest = readFileSync(
      path.resolve(__dirname, '../build/react-client-manifest.json'),
      'utf8'
    );
    moduleMap = JSON.parse(manifest);
  }
  pipeToNodeWritable(React.createElement(ReactApp, props), res, moduleMap);
}

The NextJS demo is optimized:
https://github.com/vercel/next-server-components/blob/master/libs/send-res.js

What happens when deploying breaking changes?

If we release a new version of the app, maybe containing breaking changes eg.:

  • the server component require more props in the new version
  • Maybe the server component was removed
  • depend on a new client component

how is the app running on the browser updated / invalidated to support those extra props?

Suggestion: Stale While Revalidate cache management

The demo is great and the performances are impressive.

More and more, Web apps use State While Revalidate for remote data fetching thanks to excellent libraries as SWR, react-query and Apollo Client.

It makes sense for React Server Components to support this pattern too.

In the demo, the data stored in the Postgres database could be changed by another user.
In the current implementation, only mutations done by the current app user refresh the cache.
With State While Revalidate remote data fetching, the changes done by other users will be reflected.

It would be great to see this feature demonstrated with React Server Components even in a minimal version.

useServerResponse: Infinite render when deactivating cache

It seems that the cache usage is mandatory for this demo project.
In useServerResponse, when commenting the following block of code:

  if (response) {
    return response;
  }

The app enters in a infinite loop of renders (see the screenshot attached, I've added a console log to debug).

The expected behavior is just to not use the cache and re-fetch, but there are probably other technical requirements introduced by the React Server Components architecture.

Screenshot 2020-12-27 at 16 41 06

Setup: Node v14 is required

With Node v12, I get the error "Error: Cannot find module 'fs/promises'"
With Node v13, the server is not running, "node: bad option: --conditions=react-server" in the logs.

Fixed with Node v14.

Element type is invalid

Uncaught Error: Element type is invalid. Received a promise that resolves to: [object Object]. Lazy element type must resolve to a class or function.

Webpack 5 Support

Seems there is a new chunk graph API and you'll need to utilize it to support webpack 5.

Error: Module.id: There was no ChunkGraph assigned to the Module for backward-compat (Use the new API)

Can't use destructuring assignment in server code

As mentioned (in more detail) at facebook/react#23126 (comment)

If you use destructuring assignment in a server component, you get a babel error:

/server-components-demo/src/App.server.js:141
undefined
      ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /server-components-demo/node_modules/@babel/runtime/helpers/esm/slicedToArray.js from /server-components-demo/src/App.server.js not supported.
Instead change the require of slicedToArray.js in /server-components-demo/src/App.server.js to a dynamic import() which is available in all CommonJS modules.

Demo

Leave a comment

Failed to build

Windows 10, Node 15.4.0, NPM 7.0.15

[0] Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: server-components-demo\node_modules\@babel\runtime\helpers\esm\createForOfIteratorHelper.js
[0] require() of ES modules is not supported.
[0] require() of server-components-demo\node_modules\@babel\runtime\helpers\esm\createForOfIteratorHelper.js from server-components-demo\node_modules\marked\src\marked.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
[0] Instead rename createForOfIteratorHelper.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from server-components-demo\node_modules\@babel\runtime\helpers\esm\package.json.
[0]
[0]     at new NodeError (node:internal/errors:278:15)
[0]     at Module._extensions..js (node:internal/modules/cjs/loader:1125:13)
[0]     at Object.newLoader [as .js] (server-components-demo\node_modules\pirates\lib\index.js:104:7)
[0]     at Module.load (node:internal/modules/cjs/loader:973:32)
[0]     at Function.Module._load (node:internal/modules/cjs/loader:813:14)
[0]     at Module.require (node:internal/modules/cjs/loader:997:19)
[0]     at require (node:internal/modules/cjs/helpers:92:18)
[0]     at Object.<anonymous> (server-components-demo\node_modules\marked\src\marked.js:5:58)
[0]     at Module._compile (node:internal/modules/cjs/loader:1108:14)
[0]     at Module._compile (server-components-demo\node_modules\pirates\lib\index.js:99:24) {
[0]   code: 'ERR_REQUIRE_ESM'
[0] }

Authentication ?

Could we use useContext for react-server components to deal with currentUserId ?

Webpack isServer:true

What do you think it is a good implementation for the webpack plugin for the server?

It should be similar to react server dom webpack node custom register?

Should we replace .client code with only their reference?

Failed to compile on windows

Windows 10, Node 14.9.0, npm 6.14.8

TypeError: D:\Projects\personal\server-components-demo\node_modules\safe-buffer\index.js: Cannot read property 'from' of undefined
    at Converter.toBase64 (D:\Projects\personal\server-components-demo\node_modules\convert-source-map\index.js:61:28)
    at Converter.toComment (D:\Projects\personal\server-components-demo\node_modules\convert-source-map\index.js:65:21)
    at generateCode (D:\Projects\personal\server-components-demo\node_modules\@babel\core\lib\transformation\file\generate.js:78:76)
    at run (D:\Projects\personal\server-components-demo\node_modules\@babel\core\lib\transformation\index.js:55:33)
    at run.next (<anonymous>)
    at Function.transform (D:\Projects\personal\server-components-demo\node_modules\@babel\core\lib\transform.js:27:41)
    at transform.next (<anonymous>)
    at evaluateSync (D:\Projects\personal\server-components-demo\node_modules\gensync\index.js:251:28)
    at Function.sync (D:\Projects\personal\server-components-demo\node_modules\gensync\index.js:89:14)
    at Object.transform (D:\Projects\personal\server-components-demo\node_modules\@babel\core\lib\transform.js:36:54) {
  code: 'BABEL_GENERATE_ERROR'
}

Suggestion: new router

This demo looks promising - I recall the mention of the need for a new router (from the video presenting the demo)? I don't know who is working on this but a few ideas:

  • Would be nice to have a router that can be used both by the server and client
  • Include localization from the beginning (I could not find a popular solution to localize URLs when using React)
  • Probably related to the previous bullet, but the localized URLs should use the same strings file as other localized string - might be good to combine some sort of i18n provider that can be used both by the server and client

Happy to join more discussions on these topics in the future.

Support for esbuild

Esbuild turns out to be very very fast then webpack, so is there any plan to switch to esbuild.

docker doesn't work

image

`postgres_1 | /usr/local/bin/docker-entrypoint.sh: sourcing /docker-entrypoint-initdb.d/init_db.sh postgres_1 | 2020-12-22 06:31:21.349 UTC [70] ERROR: role "notesadmin" already exists postgres_1 | 2020-12-22 06:31:21.349 UTC [70] STATEMENT: CREATE ROLE notesadmin WITH LOGIN PASSWORD 'password'; postgres_1 | ERROR: role "notesadmin" already exists`

How does react decide to rerender search result?

First of all, thank you for a great example 🙂️. And thank you for keeping in touch with what React dev team is working on. That's a great thing!

For example, when I create a new note with the title test and I already have search input with test, how react decide that the search result should be rerendered on the server? This thing is not clear to me 🤔️

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.