Facebook's React team has previewed Server Components, allowing developers to write code that runs on the server, speeding up data access and reducing the amount of code that has to be downloaded by the web browser.
Facebook senior software engineer Dan Abramov describes the benefits of having some React code run on the server instead of being downloaded to the browser
FetchAllTheStuffJustInCase() – it is efficient, but an ugly solution, particularly if at a later date the design changes and not all the data is needed. The alternative, he said, is a separate fetch for each component, which impacts performance.
Server Components are not the same as server-side rendering and there are no ugly screen refreshes as users navigate a page, even if the data is re-fetched. "Server Components don't render to HTML," explained Lauren Tan, who works on React Data. "They render to a special format." The framework updates the user interface in the background. It is also possible to have files that can run either on the client or on the server. Where it runs "is determined by what kind of component that is importing that shared component," said Tan. Such components are downloaded on demand when used on the client.
An advantage of Server Components is that the code can access backend resources directly, said Abramov. Sometimes the developer might want to "read data directly, and not have to access any API layer," he said.
New libraries have been added to React to support Server Components, including react-pg for accessing a Postgres database server, react-fs for working with the file system, and react-fetch for calling APIs from the server. These are called React IO libraries.
Are Server Components replacing GraphQL, a runtime and query language used by Facebook and others? "Not really," said Abramov. "At Facebook we use both server components and GraphQL," though he added that the new components might remove the need for GraphQL in some scenarios. Server Components can read GraphQL queries.
The technology is still in research and development, Abramov said, and the team is working with the Next.js developers. The recommended way to get started is to download the demo and try it out; developers are discouraged from using it more widely (even though Facebook appears to be doing so). Abramov remarked mysteriously that if coders incorporate the current preview components in production, or teach about them in courses, "it makes it more difficult for us to share our research in the open." Instead, developers are encouraged to read the RFC and add their comments there.
Early reaction is mixed. "Server Components are a great idea, it will change the game," said one, while another remarked: "I wouldn't trade a fractional increase in performance for the complexity this brings to a project, especially when I have many other levers I can pull before pulling this one." ®