编程知识 cdmana.com

What are react RFC server components and what are their uses

Reprinted from : The magician Carson official account

12 month 21 Japan ,React The team announced a new proposal Server Components.

Along with this proposal , There's an hour left Video Explanation 、 Available for operation Demo、 Detailed introduction .

so ,React The team attaches great importance to this proposal . This article will explain from the following aspects :

  • Server Components What is it?
  • Server Components What problems have been solved

ServerComponent What is it?

One sentence summary :

Server Components It runs on the server side React Components .

Why ? This sum Server rendering (SSR) What's the difference? ?

comparison SSR Render the component to fill in the content on the server side HTML character string , And on the client side hydrate After use .Server Components More like our common components written on the client side , It's just that his operating environment is the server side .

We can divide components into :

  • Providing data Container components
  • Rendering data and providing data interaction Interactive components

for instance ,Note Components are Container components , He's responsible for requesting and caching data .NoteEditor It's rendering note Data and perform user interaction Interactive components .

function Note(props) {
  const [note, setNote] = useState(null);
  useEffect(() => {
    fetchNote(props.id).then(noteData => {
      setNote(noteData);
    });
  }, [props.id]);
  
  if (note == null) {
    return "Loading";
  } else {
    return <NoteEditor note={note}/>
  }
}

As the example shows , We can pass in useEffect Request and save the returned data in state in .

such 「 request - Rendering 」 Patterns will encounter what is known as waterfall The problem of :

It's like a waterfall flowing down ,NoteEditor Need to wait Note request note Only after success can you start rendering .

When Interactive components The more data sources you rely on ,waterfall The problem will be more obvious .

Theoretically , If React Smart enough , You can be in Server side perform Container components The rendering logic of , stay client perform Interactive components The rendering logic of .

According to this idea , Here is a component tree that is completely rendered on the client side :

It can be divided into : stay Server side Running Container components And in client Running Interactive components .

Which runs on the server side Container components Namely Server Component.

ServerComponent The meaning of

since ServerComponent stay Server side function , Nature is closer to all kinds of IO( Request database 、 Read the file 、 cache ...).

The above example can be directly from database obtain note data , At the same time with the help of Suspense, Using synchronous writing .

function Note(props) {
  const note = db.notes.get(props.id);
  if (note == null) {
    return "Loading";
  }
  return <NoteEditor note={note}/>
}

Nature is closer to the back end

Any other data source just needs to go through React Provided API Simple packaging , To support Suspense, You can access ServerComponent in . Nature is closer to the back end .

solve waterfall

The difference in SSR Transmission of HTML character string .ServerComponent Will Note Components and their components from IO The requested data is serialized to be similar to JSX Data structure of , With flow To the front end :

The client gets the data filled in directly at run time flow , With the help of Concurrent Mode perform streaming Rendering .

0 Packing volume

Suppose we develop a MD Editor . The server passes it to the front end MD Format string .

We need to introduce at the front end will MD It can be interpreted as HTML String Library . This library has 206k.

import marked from 'marked'; // 35.9K (11.2K gzipped)
import sanitizeHtml from 'sanitize-html'; // 206K (63.3K gzipped)
function NoteWithMarkdown({text}) {
  const html = sanitizeHtml(marked(text));
  return (/* render */);
}

adopt ServerComponent How can we solve this problem ?

Just simply put NoteWithMarkdown Marked as ServerComponent, Will introduce and parse MD This part of logic is placed in Server side perform .

ServerComponent It doesn't increase the packaging volume of front-end projects . In this case , One time reduces the front end for us 206K (63.3K gzipped) The packing volume and analysis of MD Time for .

Automatic code segmentation

By using React.lazy Can implement components of dynamic import. Before , This requires us to switch components / Routing is performed manually . stay ServerComponent in , It's all done automatically .

 picture

In the diagram above , The list on the left is ServerComponent, When you click on one of the cards , The corresponding data of components will be loaded dynamically .

better ahead-of-time (AOT) Optimize

Vue Use as a door Template language Framework , Template language The fixed writing method enables it to optimize the template content during compilation .

because JSX just JS The grammar sugar of ,React It's hard to optimize at compile time .

ServerComponent More restrictions on components ( Out of commission useStateuseEffect...). These restrictions are from the side AOT Provide more optimization clues .

ServerComponent Use

Now let's rewrite a Notepad Component explanation ServerComponent Use :

// Note.js 
import fetchData from './fetchData'; 
import NoteEditor from './NoteEditor';
function Note(props) {
  const {id, isEditing} = props;
  const note = fetchData(id);
  
  return (
    <div>
      <h1>{note.title}</h1>
      <section>{note.body}</section>
      {isEditing 
        ? <NoteEditor note={note} />
        : null
      }
    </div>
  );
}

Note The main function of a component is based on props Incoming id Request corresponding note data .

NoteEditor Used to show and modify note.

among fetchData Method is used to get data , The state of data loading is determined by the Suspense complete .

You can see , The interaction part is made up of NoteEditor complete ,Note The main function is to obtain and transfer data .

What we're going to do is Note Turn into ServerComponent.

//  Be careful 
// Note.server.js - Server Component
//  Be careful 
import db from 'db.server'; 
//  Be careful 
import NoteEditor from './NoteEditor.client';
function Note(props) {
  const {id, isEditing} = props;
  const note = db.posts.get(id);
  
  return (
    <div>
      <h1>{note.title}</h1>
      <section>{note.body}</section>
      {isEditing 
        ? <NoteEditor note={note} />
        : null
      }
    </div>
  );
}

Yes 3 Some changes that need attention , Let's take a look at :

  1. Note.js Change the file name to Note.server.js On behalf of this is Server Component.
  2. Note.server.js Running on the server , We don't need the client's fetchData Method , Direct access to database , So here we call db.server Methods provided
  3. NoteEditor Used to show and modify note. This is controlled by the interaction of the client user , So change the file name to NoteEditor.client It means it's a Client Component.

summary

Nothing new in the sun . Early front-end interaction was simple , Just as a server View layer .

As the front-end interaction becomes more complex , There is a front-end framework led client rendering (CSR).

In order to solve the first screen rendering speed 、SEO problem , Server side rendering appeared (SSR), Back to what I used to be View The starting point of the layer , It's just that the granularity of control is finer .

ServerComponent The emergence of the proposal , Indicates React Our long-term goal : Will be right View Layer control is refined to the component level .

Why 「 Long term goals 」ServerComponent The premise of landing is Concurrent Mode The production environment is stable , Let's look forward to 2021 Years! .

Reference material

[1] Video Explanation : https://www.youtube.com/watch...

[2] Demo: https://github.com/pomber/ser...

版权声明
本文为[robin]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224104311371w.html

Scroll to Top