async-server-component

1.0.2 • Public • Published

async-server-component

A sharable react component for re-rendering the server rendered html initially during the client render.

This prevents a flash of unstyled content during rendering a dynamically imported component.

Taken from solutions provided in this issue in React.

This component is used for two different use cases:

Suspense on the server

Preserve the server rendered loading state when client component is dynamically imported:

import AsyncServerComponent from "async-server-component";
import { asyncComponent } from "react-async-component";
 
const Header = asyncComponent({
  resolve: () => import(/* webpackChunkName: 'header' */ "./header"),
  LoadingComponent: () => (
    <AsyncServerComponent asyncLoading={'[data-async-loading="header"]'} />
  ),
});

Server side treeshaking

If its possible to create a server and client version of a component, then <AsyncServerComponent /> can prevent a component from being loaded on the client, potentially reducing bundle size.

The example below conditionally renders the more expensive logged in version, but can it can be safely excluded for logged out users, reducing the bundle size:

const ServerComponent = ({ loggedIn }) => {
  return <div>{loggedIn ? <Header /> : <LoggedoutStaticHeader />}</div>;
};
 
const ClientComponent = ({ loggedIn }) => {
  return (
    <div>
      {loggedIn ? (
        <Header />
      ) : (
        <AsyncServerComponent asyncLoading={'[data-async-loading="header"]'} />
      )}
    </div>
  );
};

Readme

Keywords

none

Package Sidebar

Install

npm i async-server-component

Weekly Downloads

0

Version

1.0.2

License

none

Unpacked Size

2.48 kB

Total Files

3

Last publish

Collaborators

  • matthoffner