react icon indicating copy to clipboard operation
react copied to clipboard

Bug: Using useSyncExternalStore with SSR and no getServerSnapshot results in error

Open kentcdodds opened this issue 2 years ago • 7 comments

React version: 18.2.0

Steps To Reproduce

  1. Use useSyncExternalStore and omit the third argument
  2. Server render this and observe the error

Link to code example: https://stackblitz.com/edit/stackblitz-starters-n87byy

import {useSyncExternalStore, Suspense, createElement} from 'react'
import * as ReactDOMServer from 'react-dom/server'

const mediaQuery = '(max-width: 600px)'
function getSnapshot() {
  return window.matchMedia(mediaQuery).matches
}

function subscribe(callback) {
  const mediaQueryList = window.matchMedia(mediaQuery)
  mediaQueryList.addEventListener('change', callback)
  return () => {
    mediaQueryList.removeEventListener('change', callback)
  }
}

function NarrowScreenNotifier() {
  const isNarrow = useSyncExternalStore(subscribe, getSnapshot)
  return createElement(
    'div',
    {},
    isNarrow ? 'You are on a narrow screen' : 'You are on a wide screen',
  )
}

function App() {
  return createElement('div', {
    children: [
      "Here's the notifier:",
      createElement(Suspense, {
        fallback: '',
        children: createElement(NarrowScreenNotifier),
      }),
    ],
  })
}

console.log(ReactDOMServer.renderToString(createElement(App)))

The current behavior

The output of running this program shows:

<div>Here&#x27;s the notifier:<!--$!--><template data-msg="Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering." data-stck="
    at NarrowScreenNotifier
    at Suspense
    at div
    at App"></template><!--/$--></div>

The expected behavior

As noted in the useSyncExternalStore server rendering docs:

If there is no meaningful initial value for the server rendering, omit this argument to force rendering on the client.

So omitting the third argument is what you're supposed to do to force client-only rendering for cases like this (where it's impossible to know on the server what the value should be).

However, when I attempt to omit the third argument I get hydration errors. In a more complete example with Remix, I get 500 errors on the server when I do this: https://stackblitz.com/edit/remix-run-remix-su1mep

Suggestion

Either:

  1. Do not error out when omitting the third argument and instead render the suspense fallback until the client can take over
  2. Update the docs to not recommend omitting the third argument

kentcdodds avatar Feb 23 '24 16:02 kentcdodds

@kentcdodds In the The current behavior section, I believe it was a successful render.

I replaced the last line with this:

try {
  console.log(ReactDOMServer.renderToString(createElement(App)));
  console.log('✅ Rendered successfully');
} catch (e) {
  console.error('❌ Render error:', e);
}

The output showed that it is a successful render:

<div>Here&#x27;s the notifier:<!--$!--><template data-msg="Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering." data-stck="
    at NarrowScreenNotifier
    at Suspense
    at div
    at App"></template><!--/$--></div>
✅ Rendered successfully

The link “force rendering on the client” in your quote points to a docs page about using <Suspense> boundaries to handle errors on the server, which seems to be what useSyncExternalStore does on the server in absence getServerSnapshot.

So this is what I understand would happen:

  1. useSyncExternalStore called on server without getServerSnapshot. As such, it throws an error
  2. Suspense fallback is rendered instead, with <!--$!--><template data-msg="…" data-stck="…">…</template><!--/$-->. I believe this is for propagating SSR errors to the client, so it can be displayed in the JS console.

So by throwing error, the Suspense boundary catches it, which as a side-effect, force rendering on the client.

In your Remix example I don’t see 500 errors in server side. I see fallback rendered properly, and then replaced by the client-side message.

image

If I remove the Suspense boundary…

 function App() {
   return createElement('div', {
     children: [
       "Here's the notifier:",
+      createElement(NarrowScreenNotifier),
-      createElement(Suspense, {
-        fallback: '',
-        children: createElement(NarrowScreenNotifier),
-      }),
     ],
   });
 }

I get a real render error:

❌ Render error: Error: Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.
    at Object.useSyncExternalStore (/home/projects/stackblitz-starters-a5wwtm/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:5218:11)
    at Module.useSyncExternalStore (/home/projects/stackblitz-starters-a5wwtm/node_modules/react/cjs/react.development.js:1676:21)
    at NarrowScreenNotifier (/home/projects/stackblitz-starters-a5wwtm/index.js:31:27)
    at renderWithHooks (/home/projects/stackblitz-starters-a5wwtm/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:5662:16)
    at renderIndeterminateComponent (/home/projects/stackblitz-starters-a5wwtm/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:5735:15)
    at renderElement (/home/projects/stackblitz-starters-a5wwtm/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:5950:7)
    at renderNodeDestructiveImpl (/home/projects/stackblitz-starters-a5wwtm/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6108:11)
    at renderNodeDestructive (/home/projects/stackblitz-starters-a5wwtm/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6080:14)
    at renderNode (/home/projects/stackblitz-starters-a5wwtm/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6263:12)
    at renderChildrenArray (/home/projects/stackblitz-starters-a5wwtm/node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js:6215:7)

The same goes for Remix example:

image

So from my perspective I think it works as documented?

dtinth avatar Feb 23 '24 16:02 dtinth

I'm not seeing a hydration error in the Remix example. There is an error logged but that comes from onRecoverableError.

If I hydrate the renderToString markup with hydrateRoot, I get the final expected output: https://codesandbox.io/p/sandbox/romantic-minsky-vxwnvj. There is still a recoverable error logged which is expected.

As far as I can tell, the only bug is the 500 returned from Remix? What is Remix using to render on the server? Might be we need to adjust documentation

eps1lon avatar Feb 23 '24 16:02 eps1lon

Thank you both. @eps1lon your example was especially helpful. Thanks! I think if this is the recommended way to handle this situation, defaulting to logging an error is kind of confusing 🤔 But at least I can opt-out by having an empty onRecoverableError function. At the very least I think the docs could be updated to mention the use of onRecoverableError to handle the error that shows up in the console.

kentcdodds avatar Feb 23 '24 16:02 kentcdodds

Yeah we should update the docs to mention the error will still be logged as a recoverable error.

We default to logging an error when onRecoverableError is missing because otherwise you would miss errors for legit bugs. For example, if we didn't log this here, and you accidentally forgot the server snapshot arg, you wouldn't catch it.

onRecoverableError is the mechanism to ack deopts like this. You should only ignore the known errors though, otherwise you may miss errors for new issues that are actual bugs causing deopts.

rickhanlonii avatar Feb 23 '24 17:02 rickhanlonii

Good call 👍 Thanks @rickhanlonii!

kentcdodds avatar Feb 23 '24 17:02 kentcdodds

I might be wrong but I think this is another case where a built-in API for "continue this on the client" (like the experimental unstable_postpone) would allow to differentiate intentional vs unintentional errors.

In the future, that is.

gaearon avatar Feb 23 '24 22:02 gaearon

I found this page because of this very same error. I agree with @kentcdodds that the documentation is clear; but I'll suggest that perhaps it's the error message that isn't. For instance, pointing people to the documentation might help.

raydot avatar Mar 08 '24 20:03 raydot

This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

github-actions[bot] avatar Jun 06 '24 21:06 github-actions[bot]

Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!

github-actions[bot] avatar Jun 13 '24 21:06 github-actions[bot]