Bug: Using useSyncExternalStore with SSR and no getServerSnapshot results in error
React version: 18.2.0
Steps To Reproduce
- Use useSyncExternalStore and omit the third argument
- 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'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:
- Do not error out when omitting the third argument and instead render the suspense fallback until the client can take over
- Update the docs to not recommend omitting the third argument
@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'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:
useSyncExternalStorecalled on server withoutgetServerSnapshot. As such, it throws an error- 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.
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:
So from my perspective I think it works as documented?
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
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.
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.
Good call 👍 Thanks @rickhanlonii!
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.
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.
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!
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!