react-spectrum icon indicating copy to clipboard operation
react-spectrum copied to clipboard

TimeField component and hydration error (Next.js)

Open pasqualevitiello opened this issue 2 years ago โ€ข 18 comments

Provide a general summary of the issue here

The TimeFied component triggers a hydration error in Safari and Firefox, but seems to work correctly in Chrome.

๐Ÿค” Expected Behavior?

No hydration error expected

๐Ÿ˜ฏ Current Behavior

Screenshot 2024-10-10 at 18 10 50

๐Ÿ’ Possible Solution

No response

๐Ÿ”ฆ Context

No response

๐Ÿ–ฅ๏ธ Steps to Reproduce

Repo: https://github.com/pasqualevitiello/rac-timefield-issue Demo link: https://rac-timefield-issue.vercel.app/

Version

rac 1.4.0

What browsers are you seeing the problem on?

Firefox, Safari

If other, please specify.

No response

What operating system are you using?

macOS 15

๐Ÿงข Your Company/Team

No response

๐Ÿ•ท Tracking Issue

No response

pasqualevitiello avatar Oct 10 '24 16:10 pasqualevitiello

This is caused by the format of the date on the node server and within Firefox/Safari being different. It could be fixed with the suppressHydrationWarning property. Other fixes include using useEffect to hydrate a component or create the first instance of a date in the browser.

ktabors avatar Oct 10 '24 21:10 ktabors

Thanks! Not sure to understand how to use suppressHydrationWarning. Adding the attribute to any of the components does not silence the warning.

pasqualevitiello avatar Oct 11 '24 08:10 pasqualevitiello

It goes directly on the element, not a prop on the React Aria component (currently).

reidbarber avatar Oct 14 '24 14:10 reidbarber

I feel stupid for not figuring out how to resolve the issue. Would you mind to provide an example based on this component?

pasqualevitiello avatar Oct 14 '24 15:10 pasqualevitiello

I believe what is being mentioned above would need to be implemented on our end since it needs to be set on the div/input/something rendered by the TimeField component internally. That being said, https://rac-timefield-issue.vercel.app/ doesn't seem to error for me in Safari or Firefox.

LFDanLu avatar Oct 16 '24 22:10 LFDanLu

Cool, thanks!

pasqualevitiello avatar Oct 17 '24 07:10 pasqualevitiello

I also have this problem, the diff is basically a different kind of space character. Thanks to Next.js 15.2, we have a better view of the hydration errors.

+                     {" "}
-                     {"โ€ฏ"}

As mentioned, I can't use the suppressHydrationWarning prop directly. This happens on Firefox and Safari, not on Chrome, I can confirm. Can this be reopened?

frontsideair avatar Mar 10 '25 08:03 frontsideair

It appears that this is an issue in node, where a NARROW NO-BREAK SPACE is used instead of regular space.

const formatter = new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long' });
const segments = formatter.formatToParts(new Date())
const secondsSegmentIndex = segments.findIndex(segment => segment.type === 'second');
console.log(segments[secondsSegmentIndex+1].value.charCodeAt(0));

The above prints 8239 in node, but 32 in browsers.

This sounds related to https://github.com/nodejs/help/issues/4068, which was fixed, but the fix apparently was only applied to date.toLocaleString and formatter.format, not to formatter.formatToParts.

TimeField is using useDateFieldState, which is using DateFormatter from @internationalized/date DateFormatter is a wrapper around node's Intl.DateTimeFormat and passes formatToParts calls to the original implementation: https://github.com/adobe/react-spectrum/blob/main/packages/%40internationalized/date/src/DateFormatter.ts#L37

The best way to fix this is to fix node, but patching DateFormatter to replace the NARROW NO-BREAK SPACE with a regular space is also an option.

dklymenk avatar Aug 29 '25 13:08 dklymenk

Thanks for the investigation! I've re-added this issue to our board for triage and grooming, but definitely would accept a contribution!

LFDanLu avatar Aug 29 '25 17:08 LFDanLu

If we change it in our component, won't it work in FF and Safari and break in Chrome instead of the other way around? I think the only way this gets fixed is if all the js environments agree.

It's possibly in a similar vein as https://github.com/adobe/react-spectrum/issues/8503, in that if we knew the user agent we could "do the right thing", however, that seems brittle and would just break again if/when the browsers change their implementation.

It also requires people to pass in the user agent and know that they have to do that for it to work.

snowystinger avatar Sep 01 '25 06:09 snowystinger

If we change it in our component, won't it work in FF and Safari and break in Chrome instead of the other way around? I think the only way this gets fixed is if all the js environments agree.

If you decide to go with a fix in your component, you could implement it in a non-breaking way for Chromium-based browsers. If the fix simply normalizes the return of DateFormatter.formatToParts, replacing NARROW NO-BREAK SPACE with a regular space, it will make the component render with regular spaces in Node AND all of the browsers. With that, there should be no hydration errors regardless of your browser or node version.

I fully understand that a fix in V8 is preferred, as that would eventually make its way into both Node and Chromium, but it might take a while. A temporary fix in @internationalized/date would be faster and can eventually be removed once stable Chromium and Node get shipped with the real fix.

I'll try to come up with a PR to update @internationalized/date DateFormatter this week.

dklymenk avatar Sep 01 '25 17:09 dklymenk

Ah, yep, I see what you're saying. I over thought it. Thanks.

snowystinger avatar Sep 02 '25 00:09 snowystinger

I have submitted a PR with the character normalization logic. https://github.com/adobe/react-spectrum/pull/8826

With that, AM/PM should always be preceded with a regular space regardless of the runtime environment.

dklymenk avatar Sep 06 '25 22:09 dklymenk

I got some more information on the direction this is headed in browsers https://github.com/tc39/ecma402/issues/1028#issuecomment-3305090510

An interesting suggestion from that is to use ICU4X. Because we are a library, we do not want people who are not using SSR to pay the price of this additional dependency. But perhaps through our I18nProvider we could allow people to specify a different implementation of Intl.

Something like

function I18nProvider(props) {
  let ctxIntl = props.Intl ?? Intl;
  return <I18nContext.Provider ctxIntl...
}

and then anywhere we use Intl, we grab it from the context instead.

We have some non hook and non component functions which also make use of Intl, we'd need to add additional optional args to all of those. Such as in https://github.com/adobe/react-spectrum/blob/6e467f870a596c82014895934f4e60834cba0550/packages/%40internationalized/date/src/DateFormatter.ts#L135

snowystinger avatar Sep 18 '25 02:09 snowystinger

I also have this problem, the diff is basically a different kind of space character. Thanks to Next.js 15.2, we have a better view of the hydration errors.

+                     {" "}
-                     {"โ€ฏ"}

As mentioned, I can't use the suppressHydrationWarning prop directly. This happens on Firefox and Safari, not on Chrome, I can confirm. Can this be reopened?

I have the exact same issue @frontsideair , how did you fix it?

(
		<AriaTimeField 
		hideTimeZone
		aria-label="Pick a time"
		defaultValue={props.defaultValue}
		className={cx(
                "flex rounded-lg bg-primary px-2.5 py-2 text-md shadow-xs ring-1 ring-primary ring-inset focus-within:ring-2 focus-within:ring-brand",
                typeof props.className === "string" && props.className,
            )}
		isDisabled={isDisabled}
		{...props}
			>
			<DateInput>
				{(segment) => <DateSegment segment={segment} 
				        className={cx(
                        "rounded px-px text-primary tabular-nums caret-transparent focus:bg-brand-solid focus:font-medium focus:text-white focus:outline-hidden",
                        // The placeholder segment.
                        segment.isPlaceholder && "text-placeholder uppercase",
                        // The separator "/" segment.
                        segment.type === "literal" && "text-fg-quaternary",
                    )}
					/>}
			</DateInput>
		</AriaTimeField>
	)

i'm on [email protected], [email protected], @internationalized/[email protected] and node 22.17

benjyAuthi avatar Jan 31 '26 22:01 benjyAuthi

@benjyAuthi The most straightforward thing you can do is only render the component on the client, rendering a skeleton on the server.

If you absolutely must render the element on the server, you could try and manually normalize the space character as you pass segment to DateSegment. I haven't tried that approach, but it might just work for you, especially if you only care about English. If your scope is broader than English, you'll never catch a break as discrepancies between node and browsers go beyond just space characters for a lot of locales.

dklymenk avatar Jan 31 '26 23:01 dklymenk

With the latest release and the render prop you can prevent the issue as below. DateSegment itself does not pass through suppressHydrationWarning

I think it is fine if react does not patch the different whitespace character.

<DateSegment
  segment={segment}
  render={(props) => (
    <span {...props} suppressHydrationWarning />
  )}
/>

We have seen similar errors with different hyphens we formatting numbers or dates, depending on if the component is server-rendered or not. With hyphens, you likely want react not to patch the diff, otherwise your interface can jump depending in the hyphen (or in the above case spacing) width.

beckerei avatar Feb 18 '26 15:02 beckerei

Alternative solution that could be implemented within the lib is using useSyncExternalStore for getting a client and server snapshot, both could call the same function and even though outputs are different on client and server react would not give an hydration error - as this is expected.

It would work both in hybrid client/server and client only applications.

But it might be overkill here.

beckerei avatar Feb 19 '26 16:02 beckerei