Giter Club home page Giter Club logo

react-ssr-prepass's Introduction

react-ssr-prepass

Build Status Test Coverage NPM Version Maintenance Status

react-dom/server does not have support for suspense yet.
react-ssr-prepass offers suspense on the server-side today, until it does. ✨

react-ssr-prepass is a partial server-side React renderer that does a prepass on a React element tree and suspends when it finds thrown promises. It also accepts a visitor function that can be used to suspend on anything.

You can use it to fetch data before your SSR code calls renderToString or renderToNodeStream.

⚠️ Note: Suspense is unstable and experimental. This library purely exists since react-dom/server does not support data fetching or suspense yet. This two-pass approach should just be used until server-side suspense support lands in React.

The Why & How

It's quite common to have some data that needs to be fetched before server-side rendering and often it's inconvenient to specifically call out to random fetch calls to get some data. Instead Suspense offers a practical way to automatically fetch some required data, but is currently only supported in client-side React.

react-ssr-prepass offers a solution by being a "prepass" function that walks a React element tree and executing suspense. It finds all thrown promises (a custom visitor can also be provided) and waits for those promises to resolve before continuing to walk that particular suspended subtree. Hence, it attempts to offer a practical way to use suspense and complex data fetching logic today.

A two-pass React render is already quite common for in other libraries that do implement data fetching. This has however become quite impractical. While it was trivial to previously implement a primitive React renderer, these days a lot more moving parts are involved to make such a renderer correct and stable. This is why some implementations now simply rely on calling renderToStaticMarkup repeatedly.

react-ssr-prepass on the other hand is a custom implementation of a React renderer. It attempts to stay true and correct to the React implementation by:

  • Mirroring some of the implementation of ReactPartialRenderer
  • Leaning on React elements' symbols from react-is
  • Providing only the simplest support for suspense

Quick Start Guide

First install react-ssr-prepass alongside react and react-dom:

yarn add react-ssr-prepass
# or
npm install --save react-ssr-prepass

In your SSR code you may now add it in front of your usual renderToString or renderToNodeStream code:

import { createElement } from 'react'
import { renderToString } from 'react-dom/server'

import ssrPrepass from 'react-ssr-prepass'

const renderApp = async (App) => {
  const element = createElement(App)
  await ssrPrepass(element)

  return renderToString(element)
}

Additionally you can also pass a "visitor function" as your second argument. This function is called for every React class or function element that is encountered.

ssrPrepass(<App />, (element, instance) => {
  if (element.type === SomeData) {
    return fetchData()
  } else if (instance && instance.fetchData) {
    return instance.fetchData()
  }
})

The first argument of the visitor is the React element. The second is the instance of a class component or undefined. When you return a promise from this function react-ssr-prepass will suspend before rendering this element.

You should be aware that react-ssr-prepass does not handle any data rehydration. In most cases it's fine to collect data from your cache or store after running ssrPrepass, turn it into JSON, and send it down in your HTML result.

Prior Art

This library is (luckily) not a reimplementation from scratch of React's server-side rendering. Instead it's mostly based on React's own server-side rendering logic that resides in its ReactPartialRenderer.

The approach of doing an initial "data fetching pass" is inspired by:

Maintenance Status

Experimental: This project is quite new. We're not sure what our ongoing maintenance plan for this project will be. Bug reports, feature requests and pull requests are welcome. If you like this project, let us know!

react-ssr-prepass's People

Contributors

boygirl avatar jovidecroock avatar kitten avatar klaasman avatar marcguiselin avatar parkerziegler avatar rtsao avatar zenflow 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

react-ssr-prepass's Issues

Compatible with apollo@3 hooks ?

Hello im trying to make prepass work with apollo 3(useQuery hook) together with nextjs
I took this from docs

ssrPrepass(<App />, (element, instance) => {
 if (instance && instance.fetchData) {
    return instance.fetchData()
  }
})

My problem is since im using hooks instances of my components doesnt seem to have fetchData property
Is there any chance i can check different condition ? Or should i switch to apollos Query component ? Or theres no way to make this work ?

Any advice will be highly appreciated :)

Relationship to more "full-featured" SSR libraries?

I use react-ssr-prepass for SSR with urql.

Separately, I'm assessing how to implement code-splitting with Suspense across my app. I've never done it before and also I'm new to working with Suspense. React's docs recommend using Loadable Components.

Is this library "compatible" with something like Loadable Components? Can they be used side-by-side? How do they relate to each other?

Sorry for this n00b question. Please feel free to explain to me like I'm a five-year old (software engineer 🙂).

useState initializer called multiple times with suspense

it('should only call useState initializer once across suspensions', () => {
  let counter = 0;

  const initializeState = jest.fn(() => counter += 1);

  const Inner = jest.fn(props => {
    expect(props.value).toBe(2)
  })

  const Outer = jest.fn(() => {
    const [] = useState(initializeState);

    // Throw promise on first pass, render on 2nd pass
    if (counter === 1) {
      counter += 1;
      throw Promise.resolve()
    }

    return <Inner value={counter} />
  })

  expect(counter).toBe(0)
  return renderPrepass(<Outer />).then(() => {
    expect(initializeState).toHaveBeenCalledTimes(1);
    expect(counter).toBe(2)
  })
})

I wrote a failing test here that is expecting the state initializer to only be called once during render. I had a similar issue with useMemo(fn, []) calling fn multiple times.

Any thoughts on that?

how to use this feature with React Suspense on the server side?

const App = () => {
return (
   <RelayEnvironmentProvider environment={environment} >
          <Suspense fallback={<PageLoding/>}>
            <Layout>
              <Component {...pageProps} />
            </Layout>
          </Suspense>
        </RelayEnvironmentProvider>
);
}


 try {
             const element = <App />

                await ssrPrepass(element);
                return render(renderElementToString, element);
 }
catch (err) {
}

I did something as the abive, still get the two errors

rror: ReactDOMServer does not yet support Suspense.
    at ReactDOMServerRenderer.render (/Users/vidy/www/acme-admin-ui1/node_modules/react-dom/cjs/react-dom-server.node.development.js:3735:25)
    at ReactDOMServerRenderer.read (/Users/vidy/www/acme-admin-ui1/node_modules/react-dom/cjs/react-dom-server.node.development.js:3536:29)
    at renderToString (/Users/vidy/www/acme-admin-ui1/node_modules/react-dom/cjs/react-dom-server.node.development.js:4245:27)
    at render (/Users/vidy/www/acme-admin-ui1/node_modules/next/dist/next-server/server/render.js:81:16)
    at Object.renderPage (/Users/vidy/www/acme-admin-ui1/node_modules/next/dist/next-server/server/render.js:300:24)
[ event ] client pings, but there's no entry for page: /_error
Warning: Relay: Tried reading fragment `BasicLayoutQuery` declared in `useLazyLoadQuery()`, but it has missing data and its parent query `BasicLayoutQuery` is not being fetched.
This might be fixed by by re-running the Relay Compiler.  Otherwise, make sure of the following:
* You are correctly fetching `BasicLayoutQuery` if you are using a "store-only" `fetchPolicy`.
* Other queries aren't accidentally fetching and overwriting the data for this fragment.
* Any related mutations or subscriptions are fetching all of the data for this fragment.
* Any related store updaters aren't accidentally deleting data for this fragment.
Warning: Relay: Expected to have been able to read non-null data for fragment `BasicLayoutQuery` declared in `useLazyLoadQuery()`, since fragment reference was non-null. Make sure that that `useLazyLoadQuery()`'s parent isn't holding on to and/or passing a fragment reference for data that has been deleted.

React 18 shim

Now that react-dom/server support data fetching and suspense as of react-dom@18, I was wondering how much work it would be to replace react-ssr-prepass and it turned out to be pretty blissful. So I'm writing this issue to share a cheeky drop-in replacement, I came by this repo earlier looking for such a thing so I figured I would provide it now that I figured it out:

import { renderToPipeableStream } from "react-dom/server";
await new Promise((onAllReady, onError) => renderToPipeableStream(<App />, { onAllReady, onError }));

Here's the diff in my app
image

Lib not rendering components in same order

Hi!

First, thank you for the lib 👏 !

I am trying to run through the React tree to get all the elements that are need pre-rendering (API fetching). This happends successfully but the components are not rendered in the same order as with renderToString. The problem is I have unique ids (through react-uid) that should be the same between server rendering and client rendering and that are dependants on the order of rendering.

This is my code:

  try {
    await ssrPrepass(
      sheetsPrepass.collect(reactElement),
      (element, instance) => {
        if (element && element.type && element.type.getInitialProps) {
          store.dispatch(
            enqueuePrefetchedComponent(`${componentName}-${element.props.uid}`),
          );
          return store.dispatch(element.type.getInitialProps(element.props));
        }
        return Promise.resolve();
      },
    );
  } catch (error) {
    if (isRedirect(error)) {
      return { redirect: error.uri };
    }
    throw error;
  }

I have even tried to run ssrPrepass a second time (after API fetching) and the rendering is done exactly on the same order as the first time. I believe that ssrPrepass make us able to perform actions before rendering, so this shouldn't be a problem.

I don't know how I can give more information or even if this is something that should be fixed.

Thank you 🚀

Usage of secret internals breaks compatibility with Preact

I am not sure if you intend to be compatible with Preact but you are using

React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED

which breaks compatibility with Preact. This also means Preact cannot be used with Next (at least not Preact X, since there is no equivalent for this.

Problems with actions on redirect

Hi.

I've faced with a problem during SSR.
I send GraphQL query on page 1 by action creator. Process response in success action creator and if some property is true I make redirect to another URL. New URL also send query, but ssrPrepass ignore redirect and second query doesn't provided to initial state and page looks incorrect.

`

const visitor = (el, instance) => {
  if (instance && instance.fetchData) {
    return instance.fetchData()
  }
  ...
}

await ssrPrepass(App, visitor)

`

P.S.: I used react-tree-walker before and it worked with redirects correct.

what could we do while ssr-prepass and renderToNodeStream

There is a gap between we are waiting to ssrPrepass(element) finish (api calls finish) and renderToNodeStream which increase TTFB, is there any idea about doing sth in this gap.

for example if we could get helmet needs data and stream header before finishing the whole ssr-prepass promise..

Functional components

How do I add fetchData on Functional components? I get undefined on instance visitor function.

This works.

class Home extends React.Component<SampleProps> {
  // eslint-disable-next-line @typescript-eslint/no-useless-constructor
  constructor(props: SampleProps) {
    super(props);
  }

  fetchData = function () {
    console.log("Home -> fetchData -> fetchData", this);
    return fetch("https://google.se");
  };

  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

but this doesnt

const Home = (props) => {
  return <h1>Hello, {props.name}</h1>;
};

Home.fetchData = function () {
  console.log("Home -> fetchData -> fetchData", this);
  return fetch("https://google.se");
};

any clue why?

Does this do a "double render" to catch what needs to be SSRd?

Hey!

Checking out this project and wanted to get some clarification.

When you are walking the tree in the prepass, is it operating on a double render mechanism of sorts? prepass walks and either renders or executes parts of reacts renderer to suspend on the flushed chunks. Noticed any performance drags with your current implementation method compared to other mechanisms like react-universal-component or loadable-components?

Interested in learning a little more about this project as I was getting ready to patch react-dom.

Looks pretty neat so far!

Provide ESM build

Hello, thanks for this package! Finally possible to make easy SSR with react.
I'm using this in vite-ssr and vitedge, which basically do SSR with Vite and React/Vue in Node or Cloudflare Workers.

Vite tends to complain about packages that don't provide an ESM build, and it requires some manual setup to make it work.
It would be great if react-ssr-prepass exported an ESM build directly instead of only CJS.

Thanks!

using ssr-prepase after 1.3.0 react 17

Ive been reading the suspense test cases for a couple hours now and I just cannot get this to work.

I expect when this renders to see <h1 id="async-h1">hello</h1> but the thrown promise is bubbling all the way out and failing the build with a thrown object. I am sure I am doing something wrong here.

import React, {useState} from 'react';

function Inner({value}) {
    return (<h1 id="async-h1">{value}</h1>)
}

function Async() {
  const fetchThing = () => {
      throw Promise.resolve('hello');
  };
  const [value] = useState(fetchThing);
  return (<Inner value={value}></Inner>);
}

export default Async

Custom time depending

Hi,

after adding yield time depending, sometime page is rendered without content.

Would be good to have option to change it or disable at all.

What do you think?

Potential bug with wrapped components?

Hi,

Using:

react-redux 7.2.6
react-router-dom 5.3.0
react-ssr-prepass 1.4.0

I've found if I export a component, "ComponentA" as:

withRouter(connect()(ComponentA)

I was getting the error:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

which appeared to originate from react-ssr-prepass.

I can "fix" this in my code by wrapping ComponentA differently:

connect()(withRouter(ComponentA))

I haven't got the capacity or knowledge to look into this further at the moment but wanted to highlight it in case it is an underlying bug that perhaps impacts others? (Apologies if this is just some weird quirk unique to my code!)

I did see an issue I thought might be related in the why-did-you-render repo - welldone-software/why-did-you-render#121

Where the fix appeared to be tweaking the order of the react component checks - welldone-software/why-did-you-render@983a18f

Cannot read property 'current' of undefined.

Here is the error:

TypeError: Cannot read property 'current' of undefined at Object.<anonymous> (/home/thuan/Desktop/thotot/main/node_modules/react-ssr-prepass/dist/react-ssr-prepass.development.js:842:45) at Module._compile (module.js:652:30) at Object.Module._extensions..js (module.js:663:10) at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) at Function.Module._load (module.js:497:3) at Module.require (module.js:596:17) at require (internal/module.js:11:18) at Object.<anonymous> (/home/thuan/Desktop/thotot/main/node_modules/react-ssr-prepass/index.js:4:20) at Module._compile (module.js:652:30)

Throws "ReferenceError: setImmediate is not defined" in browser

The setImmediate function (used in this package) is not present on the majority of browsers. (reference) We should replace it with something more standard and make this package more portable. The first idea (for a replacement) that comes to mind is Promise.resolve().then since I think it's the most universal/portable way.

You might wonder why I am trying to use this on the browser. (And I guess I am evidently the first to try it.) The reason is because I want to prefetch data for some pages (in my Next.js apps) before rendering/showing them, regardless of whether the rendering is happening server-side or browser-side, to get rid of unwanted <Loader/> renders where I have nothing to show the user. Instead the user waits on the previous page until the next page is ready. The user can navigate from fully-formed page to fully-formed page, within the site now, not just when entering the site (when SSR is used). It seems like generally a better UX.

[Question] - Is it faster than renderToStaticMarkup?

Hi, really interesting project!

I am currently writing a library for data fetching. Since the library uses hooks, I am not sure if I can use the visitor function to collect the promises during SSR. Currently what I am doing is calling renderToStaticMarkup repeatedly.

I am thinking to at least change renderToStaticMarkup to prepass repeatedly, if it actually helps with performance. My question is, is prepassing repeatedly faster than renderToStaticMarkup repeatedly? I did some testing but couldn't reach a conclusion.

Thanks!

Guard/check missing in areHooksInputEqual()?

Hi,

I've noticed some server logs with the following error:

TypeError: Cannot read properties of undefined (reading 'length')
at areHookInputsEqual (/var/app/current/node_modules/react-ssr-prepass/dist/react-ssr-prepass.js:295:29)
at Object.useMemo (/var/app/current/node_modules/react-ssr-prepass/dist/react-ssr-prepass.js:301:6)

Looking at the function, it appears there's no guard/check that prevDeps may be undefined?

function areHookInputsEqual(
  nextDeps: Array<mixed>,
  prevDeps: Array<mixed> | null
) {
  // NOTE: The warnings that are used in ReactPartialRendererHooks are obsolete
  // in a prepass, since these issues will be caught by a subsequent renderer anyway
  if (prevDeps === null) return false

  for (let i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
    if (!is(nextDeps[i], prevDeps[i])) return false
  }

  return true
}

I just wanted to highlight it as a potential issue. I'm not sure if it's implementation problem my end that's causing prevDeps to be undefined (rather than null)?

But just in case - in normal use - prevDeps can be undefined perhaps there should be a guard/check in place to protect against this? Could the check just be if (!prevDeps) return false instead?

Basic Usage?

I'm having trouble with basic usage of this library, on the server I have:

  const renderApp = async App => {
    const element = createElement(App)
    await ssrPrepass(element)


    return renderToString(element)
  }

    const App = () => (
      <Provider store={store}>
        <StaticRouter location={req.url} context={ctx}>
          <GlobalStyle />
          <Route component={Index} />
        </StaticRouter>
      </Provider>
    );

    const markup = await renderApp(App);

With the debugger I see that it waits for the promises thrown under Suspense and the redux store is correctly populated after waiting for prepass. But when it tries to renderToString(element) I get the error:

Error: ReactDOMServer does not yet support Suspense.

Is this not the correct usage? I couldn't any other examples of it's usage.

Thanks.

Throwing error: Hooks can only be called inside the body of a function component.

Hi, I'm trying to implement this in nextJs app. I'm currently calling it inside a component's static async getInitialProps(ctx) { but it is throwing error as i mentioned in title.

But after I commented out in this package file: src/internals/dispatcher.js

//  if (currentIdentity === null) {
//    throw new Error(
//      '[react-ssr-prepass] Hooks can only be called inside the body of a function component. ' +
//        '(https://fb.me/react-invalid-hook-call)'
//    )
//  }
 

Just to see if it will work or not, surprisingly it works great after.

May i know why we throw this error? Is there any side-effects commenting this?

Usage with react-redux

I am wondering how can I use this library in my already existing codebase. I use react, redux and react-redux to save my components state. Because of how the HoC connect() works by mapping the store state into props and injecting it into the user component, I need to re-render the parent Connect()ed component after the thrown promise is fulfilled, instead of simply re-rendering the current component instance. Can you please help me figure out how to achieve this?

Here's an example:

const MyComponent = (props) => {
  if (!props.postsFetched) {
    throw new fetchPostsFromApi.then(posts => props.savePostsToRedux(posts));
  }
  
  return posts.map(post => <h1>{post.title</h1>);
}

export default connect(
  state => ({
    postsFetched: !!state.posts,
    posts: state.posts || [],
  }),
  dispatch => ({
    savePostsToRedux: posts => dispatch({ type: 'SAVE_POSTS', payload: { posts }});
  }),
)(MyComponent);

Here's a code trace:

  1. react-ssr-prepass first renders MyComponent, catches the promise and await for it
  2. After data is fetched from the API, a Redux action is dispatched and data is saved into the store
  3. react-ssr-prepass attempts to re-render the same instance, meaning the props never get updated from the store (parent not re-called) and thus returning empty list

Any advice on how to tackle that? I am considering forking the code and queue-ing an update for the parent (or maybe the nearest <Suspense /> ancestor in the tree)

Needless to say, great job with this project and thanks in advance for your help.

Functional Components

Hello,

Curious, any suggestion on getting this process to work with functional components over classes? Thanks!

v1.5.0 Missing from Github

Hello!

I was going through dependency upgrades and while looking for the changelog, noticed that the current latest version tagged on NPM is v1.5.0 while the version on master in Github is still 1.4.0. See

"version": "1.4.0",

May you please update the repository to reflect the state of the package, or vice-versa?

Thanks!

Exception "Cannot read property 'prototype' of undefined" caused by wrong order of React.memo + Redux.connect

I found strange problem with react-ssr-prepass. In fact it seems to be problem with upgrade of react (16.11.0 -> 16.12.0) or redux (4.0.4 -> 4.0.5) or... who knows.

I've had component like:

import * as React from 'react'
import { connect } from 'react-redux'

const LinkComponent: React.FC<...> = (...) => (...)

export default connect(mapStateToProps)(React.memo(LinkComponent))

It worked with react-ssr-prepass until upgrade of react/redux/...

But after then the react-ssr-prepass started throwing exception in

export const shouldConstruct = (Comp: ComponentType<*>): boolean %checks =>

used in
return shouldConstruct(type)

that:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
TypeError: Cannot read property 'prototype' of undefined
    at render ([...]/node_modules/react-ssr-prepass/src/element.js:25:15)
    at visitElement ([...]/node_modules/react-ssr-prepass/src/visitor.js:165:23)
    at visitLoop ([...]/node_modules/react-ssr-prepass/src/visitor.js:189:24)
    at visitChildren ([...]/node_modules/react-ssr-prepass/src/visitor.js:230:22)
    at [...]/node_modules/react-ssr-prepass/src/index.js:68:5
    at processTicksAndRejections (internal/process/task_queues.js:85:5)

I've checked that is true. In generated code (node_modules/react-ssr-prepass/dist/react-ssr-prepass.development.js):

var render$3 = function(type, props, queue, visitor, element) {
  return (Comp = type).prototype && Comp.prototype.isReactComponent ? function(type, props, queue, visitor, element) {

type is undefined.

I found that the problem was in my code with line:

export default connect(mapStateToProps)(React.memo(LinkComponent))

When I changed it to (changed React.memo/Redux.connect order):

export default React.memo(connect(mapStateToProps)(LinkComponent))

problem disappear.

It is not full investigation of problem, but is clue for others with similar problem.

Dispatcher loses hooks execution order

Dispatcher loses correct hooks execution order when concurrency > 1. It tries to execute hook with state belonging to another one.

Stacktrace

TypeError: Cannot read property 'length' of undefined
    at areHookInputsEqual (/app/node_modules/react-ssr-prepass/src/internals/dispatcher.js:69:32)
    at Object.useMemo (/app/node_modules/react-ssr-prepass/src/internals/dispatcher.js:241:13)
    at useMemo (/app/node_modules/react/cjs/react.development.js:1643:21)
    at Component (/app/src/components/Component/index.ts)
    at renderWithHooks (/app/node_modules/react-ssr-prepass/src/internals/dispatcher.js:116:18)
    at render (/app/node_modules/react-ssr-prepass/src/render/functionComponent.js:52:12)
    at updateFunctionComponent (/app/node_modules/react-ssr-prepass/src/render/functionComponent.js:93:10)
    at /app/node_modules/react-ssr-prepass/src/index.js:61:18
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at prehydrateApplication (/app/src/index.ts)

Question: Some libraries cannot seemingly clear data in custom derivate...

EDIT: I figured it out, the issue was not in the walker but a rather strange implementation in those libraries that were using a global cache (guess that's why globals aren't too good), you could replicate it with react dom itself in special cases; I'd still not mind if you could check this code, just in case there's something blatant, feel free to close the question, your codebase helped me a lot.

I think what I wrote also may work as a guide for those that need to create a custom async walker, mine just has the mere basics so it's simpler to understand.

==== Original message

Back in the days of react 15 before suspense was even a thing I had come with a workaround to get promises SSR to work, it was hacky but it worked, the process was different, today I am updating that project to react 17 to use some libraries and I've been reading this source code as inspiration.

So I created this custom function based on what I understood from this library, however, there's an issue, some libraries, such as emotion-js renders (using the standard ReactDOM) differs after passing through the walker, and I can't tell why, it's as if, they refuse to be called twice; but I tested with reactDOM and they work being called twice producing the same output, my mechanism must be causing it.

You may notice the usage of getDerivedServerSideStateFromProps that is basically used to setup SSR, this is similar to NextJS, I manage to inject that state later both in server and client.

The resulting HTML hydration is equal, I get no warnings of wrong HTML, it's simply the style tags coming from emotion-js which I assume, it's somehow writing by hand.

====

Can you spot any issues?...

import uuid from "uuid";
import React from "react";

const {
  ReactCurrentDispatcher
} = (React as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

function noop(): void { }

let currentContextMap: Map<any, any> = null;

function readContextValue(context: any) {
  const value = currentContextMap.get(context);
  if (value !== undefined) {
    return value
  }

  // Return default if context has no value yet
  return context._currentValue;
}

function readContext(context: any, _: void | number | boolean) {
  return readContextValue(context)
}

function useContext(context: any, _: void | number | boolean) {
  return readContextValue(context)
}

function useState<S>(
  initialState: (() => S) | S
): [S, any] {
  return [typeof initialState === "function" ? (initialState as any)() : initialState, noop];
}

function useReducer<S, I, A>(
  reducer: any,
  initialArg: any,
  init?: any
): [S, any] {
  return [initialArg, noop];
}

function useMemo<T>(memoValue: () => T, deps: Array<any>): T {
  return memoValue();
}

function useRef<T>(initialValue: T): { current: T } {
  return {
    current: initialValue,
  }
}

function useOpaqueIdentifier(): string {
  // doesn't matter much since we don't use this anywhere for practical usage
  return "R:" + uuid.v1();
}

function useCallback<T>(callback: T, deps: Array<any>): T {
  return callback;
}

function useMutableSource<Source, Snapshot>(
  source: any,
  getSnapshot: any,
  _subscribe: any
): Snapshot {
  return getSnapshot(source._source)
}

function useTransition(): [any, boolean] {
  return [noop, false]
}

function useDeferredValue<T>(input: T): T {
  return input
}

export const Dispatcher = {
  readContext,
  useContext,
  useMemo,
  useReducer,
  useRef,
  useState,
  useCallback,
  useMutableSource,
  useTransition,
  useDeferredValue,
  useOpaqueIdentifier,
  useId: useOpaqueIdentifier,
  // ignore useLayout effect completely as usage of it will be caught
  // in a subsequent render pass
  useLayoutEffect: noop,
  // useImperativeHandle is not run in the server environment
  useImperativeHandle: noop,
  // Effects are not run in the server environment.
  useEffect: noop,
  // Debugging effect
  useDebugValue: noop
}

const symbolFor = Symbol.for;
const REACT_ELEMENT_TYPE = symbolFor('react.element');
const REACT_PORTAL_TYPE = symbolFor('react.portal');
const REACT_FRAGMENT_TYPE = symbolFor('react.fragment');
const REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
const REACT_PROFILER_TYPE = symbolFor('react.profiler');
const REACT_PROVIDER_TYPE = symbolFor('react.provider');
const REACT_CONTEXT_TYPE = symbolFor('react.context');
const REACT_CONCURRENT_MODE_TYPE = Symbol.for('react.concurrent_mode');
const REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
const REACT_SUSPENSE_TYPE = symbolFor('react.suspense');
const REACT_MEMO_TYPE = symbolFor('react.memo');
const REACT_LAZY_TYPE = symbolFor('react.lazy');

function isConstructed(element: any) {
  return element.type && element.type.prototype && element.type.prototype.isReactComponent;
}

function getType(element: any) {
  switch (element.$$typeof) {
    case REACT_PORTAL_TYPE:
      return REACT_PORTAL_TYPE
    case REACT_ELEMENT_TYPE:
    case REACT_MEMO_TYPE:                       // memo are treated as element because they are a memo of something
      switch (element.type) {
        case REACT_CONCURRENT_MODE_TYPE:
          return REACT_CONCURRENT_MODE_TYPE
        case REACT_FRAGMENT_TYPE:
          return REACT_FRAGMENT_TYPE
        case REACT_PROFILER_TYPE:
          return REACT_PROFILER_TYPE
        case REACT_STRICT_MODE_TYPE:
          return REACT_STRICT_MODE_TYPE
        case REACT_SUSPENSE_TYPE:
          return REACT_SUSPENSE_TYPE

        default: {
          switch (element.type && element.type.$$typeof) {
            case REACT_LAZY_TYPE:
              return REACT_LAZY_TYPE
            case REACT_MEMO_TYPE:
              return REACT_MEMO_TYPE
            case REACT_CONTEXT_TYPE:
              return REACT_CONTEXT_TYPE
            case REACT_PROVIDER_TYPE:
              return REACT_PROVIDER_TYPE
            case REACT_FORWARD_REF_TYPE:
              return REACT_FORWARD_REF_TYPE
            default:
              return REACT_ELEMENT_TYPE
          }
        }
      }

    default:
      return undefined
  }
}

export async function walkReactTree(element: any, contextMap: Map<any, any> = new Map()): Promise<void> {
  if (element === null || typeof element === "undefined") {
    return;
  }
  if (Array.isArray(element)) {
    await Promise.all(element.map((c) => walkReactTree(c, contextMap)));
  }

  const type = getType(element);
  const isBaseType = type === REACT_ELEMENT_TYPE && typeof element.type === "string";
  if (type === REACT_ELEMENT_TYPE && !isBaseType) {
    const isComponentType = isConstructed(element);

    if (isComponentType) {
      const instance = new element.type(element.props);

      if (instance.state === undefined) {
        instance.state = null
      }

      if (element.type.getDerivedStateFromProps) {
        const newState = element.type.getDerivedStateFromProps(instance.props, instance.state);
        if (newState) {
          instance.state = Object.assign({}, instance.state, newState)
        }
      } else if (typeof instance.componentWillMount === "function") {
        instance.componentWillMount()
      } else if (typeof instance.UNSAFE_componentWillMount === "function") {
        instance.UNSAFE_componentWillMount()
      }

      instance._isMounted = true;

      if (element.type.getDerivedServerSideStateFromProps) {
        const newState = await element.type.getDerivedServerSideStateFromProps(instance.props, instance.state);
        if (newState) {
          instance.state = Object.assign({}, instance.state, newState)
        }
      }

      try {
        const childComponent = instance.render();
        await walkReactTree(childComponent, contextMap);
      } catch (err) {
        if (typeof element.type.getDerivedStateFromError === "function") {
          const newState = element.type.getDerivedStateFromError(err);
          if (newState) {
            instance.state = Object.assign({}, instance.state, newState)
          }

          const childComponent = instance.render();
          await walkReactTree(childComponent, contextMap);
        } else {
          throw err;
        }
      }

      if (
        typeof instance.getDerivedStateFromProps !== "function" &&
        (typeof instance.componentWillMount === "function" ||
          typeof instance.UNSAFE_componentWillMount === "function") &&
        typeof instance.componentWillUnmount === 'function'
      ) {
        try {
          instance.componentWillUnmount()
        } catch (_err) {}
      }

      instance._isMounted = false;

    } else {
      const originalDispatcher = ReactCurrentDispatcher.current;

      currentContextMap = contextMap;
      ReactCurrentDispatcher.current = Dispatcher;
      const childComponent = element.type(element.props);

      currentContextMap = null;
      ReactCurrentDispatcher.current = originalDispatcher;

      await walkReactTree(childComponent, contextMap);
    }
  } else if (type === REACT_PROVIDER_TYPE) {
    const newContextMap = new Map(contextMap);
    newContextMap.set(element.type._context, element.props.value);
    await walkReactTree(element.props.children, newContextMap);
  } else if (type === REACT_CONTEXT_TYPE) {
    const contextualValue = contextMap.get(element.type._context);
    const apparentChild = element.props.children(contextualValue);
    await walkReactTree(apparentChild, contextMap);
  } else if (
    isBaseType ||
    type === REACT_FRAGMENT_TYPE ||
    type === REACT_SUSPENSE_TYPE ||
    type === REACT_STRICT_MODE_TYPE ||
    type === REACT_PROFILER_TYPE
  ) {
    await walkReactTree(element.props.children, contextMap);
  } else if (type === REACT_FORWARD_REF_TYPE) {
    const originalDispatcher = ReactCurrentDispatcher.current;

    currentContextMap = contextMap;
    ReactCurrentDispatcher.current = Dispatcher;
    const childComponent = element.type.render(element.props, element.ref);

    currentContextMap = null;
    ReactCurrentDispatcher.current = originalDispatcher;

    await walkReactTree(childComponent, contextMap);
  } else if (type === REACT_MEMO_TYPE) {
    const elementMemoed = element.type;
    await walkReactTree(elementMemoed, contextMap);
  }
}

React 18 support useId

From: trpc/trpc#1343

The dispatcher in ./src/internals/dispatcher.js is missing react 18's new useId hook.

Implementing useId

As implemented by the react core team, useId currently throws an error in ReactPartialRendererHooks.js So unfortunately, we can't use their implementation and must implement our own.

reactwg/react-18#111 and facebook/react#22644 outline the behavior of useId, originally useOpaqueIdentifier

  • useId is not a hook anymore (Edit: I'm wrong about this. See: #75)
  • useId returns a regular, non-opaque string

Thus, I propose the following:

function useId(): string {
  return 'R:' + (rendererStateRef.current.uniqueID++).toString(36)
}

React 17 support

I'm unable to install new next-urql in a next.js project because react-ssr-prepass has a peer dip on react ^16.8.0

npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0" from [email protected]
npm ERR! node_modules/next-urql/node_modules/react-ssr-prepass
npm ERR!   react-ssr-prepass@"^1.2.1" from [email protected]
npm ERR!   node_modules/next-urql
npm ERR!     next-urql@"*" from the root project

Document or remove dependency on styled-components

We should add explanation of why the requirement on styled-components exists. In my project, I use @emotion/styled, so I get a warning emitted on compilation in dev

[ warn ]  ./node_modules/react-ssr-prepass/dist/react-ssr-prepass.development.js
Module not found: Can't resolve 'styled-components' in '/Users/tom/Documents/projects/holy-rabbit/app/node_modules/react-ssr-prepass/dist'
[ info ]  ready on http://localhost:3000

`Visitor` callback `element` argument is typed incorrectly in TypeScript

The Flow type definition of the element argument is found in src/element.js:

export type UserElement = {
  type: ComponentType<DefaultProps> & ComponentStatics,
  props: DefaultProps,
  $$typeof: typeof REACT_ELEMENT_TYPE
}

In scripts/react-ssr-prepass.d.ts this type is mapped to React.ElementType<any>. However, the type defined above more accurately would be mapped to React.ReactElement<any> (see @types/react)

React 17 RFC and future maintenance

Hello 👋
First of all thanks for the great work on this library!!

I'm wanted to ask, is there any plan to support React 17, whenever it'll come out?
I suppose, what I mean is if you're going to support this library and make it compatible with newer versions of React.

Thanks a lot again, great work on this project...
🎉

Error boundaries

Currently throwing in a component that is a descendant of a component with componentDidCatch/getDerivedStateFromError results in ssrPrepass bailing entirely, that's a bit annoying and it feels like error boundaries are natural companions to Suspense("promise boundaries)".

Is this something worth putting effort into trying to support?

Visit React elements of all types while walking the tree

Hello! Firstly, thanks so much for writing and maintaining such an awesome tool. It's been a great help to me.

I've been using this library outside of the context of SSR to walk the React tree while working on some Storybook and documentation utilities. I was wondering if you'd be willing to consider allowing the visitor function to be executed on all types of React nodes, rather than just those with type UserElement.

In my scenario I have a number of React.forwardRef-wrapped components and I'd like to be able to identify them when walking the tree. For example:

import React from 'react';
import ssrPrepass from 'react-ssr-prepass';

const ForwardRefComponent = React.forwardRef((props, ref) => <div {...props} ref={ref} />);
const App = () => <ForwardRefComponent />;

let foundElement;
ssrPrepass(<App />, elem => {
  if (elem.type === ForwardRefComponent) {
    foundElement = elem;
  }
});

console.log(foundElement)
// undefined

In the case above, react-ssr-prepass's visitElement walks over the React.forwardRef-wrapped element and visits some internal React element, whose type is unknown to me.

My proposal would be able to pass some options as a third argument to ssrPrepass that would allow it to be able to visit all elements, not just those of type UserElement.

I'm planning to submit a PR and would be grateful for any feedback you have!

why HTML node showing empty or undefined?

I am checking this code to render react component on SSR
https://github.com/htdangkhoa/react-ssr-starter.

deployed latest code https://reactssrstarter.herokuapp.com/home

When I check source code HTML is not generated or In other words react component is not rendered on server

I try to debug issue below node coming undefined don't know why ?

const node = await ssrPrepass(
    <ChunkExtractorManager extractor={extractor}>
      <Provider store={store}>
        <StaticRouter location={req.url}>
          <HelmetProvider context={helmetContext}>
            <App />
          </HelmetProvider>
        </StaticRouter>
      </Provider>
    </ChunkExtractorManager>,
  );

  const markup = renderToString(node);

enter image description here

any idea ? ?

Support for React.useTransition

I'm opening this issue to keep rack of this compatibility issue with react@experimenal. If you feel like it should be addressed, I'll be happy to open a PR :)

useTransition is not supported by react-ssr-prepass.

I think it could be easily fixed by having it returned a noop: `[() => {}, false].

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.