Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix SSR tab hydration when using Strict Mode in development #2231

Merged
merged 3 commits into from
Jan 31, 2023

Conversation

thecrypticace
Copy link
Contributor

Here I've reworked the tab and panel counting mechanism to:

  1. Use Symbol() when internals aren't available (only in SSR and prod builds where double rendering does not happen)
  2. Use a generated key based on the position of the Tab in the React Virtual DOM tree when internals are available. (In dev builds whether or not Strict Mode is enabled)

The reason for this is that React’s double rendering in strict mode in development makes SSR + hydration impossible without reaching into internals. We reference the current fiber, walk up the tree of fibers, use the position of each fiber in its list of siblings to generate the key, and then use that as a "stable" reference. It is unfortunate that we have to do this at all but React doesn't give us the ability to do this using public API. The choices you have are basically: 1. No SSR at all; 2. SSR + hydration mismatches; 3. Use internals

Fixes #2220

React’s double rendering in strict mode in development makes SSR + hydration matching impossible without reaching into internals. This is unfortunate but the way react works. Production builds of React are unaffected by this but still require a consistent mechanism that works so in that case we use Symbols just like we do in SSR.
@vercel
Copy link

vercel bot commented Jan 31, 2023

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated
headlessui-react ✅ Ready (Inspect) Visit Preview 💬 Add your feedback Jan 31, 2023 at 8:23PM (UTC)
headlessui-vue ✅ Ready (Inspect) Visit Preview 💬 Add your feedback Jan 31, 2023 at 8:23PM (UTC)

@sebmarkbage
Copy link

This is going to break in React 19 fwiw. May I suggest useId. It has been available since React 18.0.

https://react.dev/reference/react/useId

@thecrypticace
Copy link
Contributor Author

yeah we'll take a look. I figured this would break but we were supporting React 16/17/18 simultaneously. Now that Headless UI v2 is React 18+ only I can revisit this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Tabs] Next.js 13 SSR hydration error
2 participants