Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(FieldStatus): avoid hydration mismatch from entry animation (#7550)

Harjoth Kharab4b905b63e9f
diff --git a/.changeset/field-status-hydration-entry-animation.md b/.changeset/field-status-hydration-entry-animation.md
new file mode 100644
index 0000000000..77b4b1f788
--- /dev/null
+++ b/.changeset/field-status-hydration-entry-animation.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `FieldStatus` (and any element using `useEntryAnimation`) no longer causes a hydration mismatch on server-rendered pages. An element that arrives in the server's HTML now hydrates without the entry style and never plays its entry animation, even when hydration runs after the page has painted; elements mounted after hydration still animate. `useEntryAnimation` no longer documents server rendering as unsupported.
+
+@harjothkhara
diff --git a/packages/core/src/hooks/useEntryAnimation.doc.mjs b/packages/core/src/hooks/useEntryAnimation.doc.mjs
index 18476b24bb..832ddc9453 100644
--- a/packages/core/src/hooks/useEntryAnimation.doc.mjs
+++ b/packages/core/src/hooks/useEntryAnimation.doc.mjs
@@ -18,12 +18,12 @@ export const docs = {
{
name: 'entryStyle',
type: 'StyleXStyles | null',
- description: 'A StyleX style object for the entry animation, or null if the element was rendered on initial page load (no animation needed).',
+ description: 'A StyleX style object for the entry animation, or null if the element was rendered on initial page load or hydrated from server HTML (no animation needed).',
},
],
usage: {
description:
- 'Returns a StyleX style for animating an element on mount. Only animates when the element is dynamically inserted after the initial page paint; elements rendered on page load are not animated. Uses Astryx motion tokens (duration, easing) for consistent animation timing. Requires "use client"; does not support SSR.',
+ 'Returns a StyleX style for animating an element on mount. Only animates when the element is dynamically inserted after the initial page paint; elements rendered on page load are not animated. Uses Astryx motion tokens (duration, easing) for consistent animation timing. Server-rendered elements hydrate without the entry style and never animate; elements mounted after hydration animate.',
bestPractices: [
{ guidance: true, description: 'Use for conditionally rendered elements like validation messages, toasts, or expanding sections.' },
{ guidance: true, description: 'Spread the returned style into stylex.props() alongside other styles.' },
@@ -39,7 +39,7 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
export const docsDense = {
description:
- 'Returns StyleX style for animating element on mount. Only animates when element dynamically inserted after initial page paint; elements rendered on page load not animated. Uses Astryx motion tokens (duration, easing) for consistent timing. Requires "use client"; does not support SSR.',
+ 'Returns StyleX style for animating element on mount. Only animates when element dynamically inserted after initial page paint; elements rendered on page load not animated. Uses Astryx motion tokens (duration, easing) for consistent timing. Server-rendered elements hydrate without entry style, never animate; elements mounted after hydration animate.',
paramDescriptions: {
preset: 'animation preset applied on mount.',
},
@@ -48,7 +48,7 @@ export const docsDense = {
},
usage: {
description:
- 'Returns StyleX style for animating element on mount. Only animates when element dynamically inserted after initial page paint; elements rendered on page load not animated. Uses Astryx motion tokens (duration, easing) for consistent timing. Requires "use client"; does not support SSR.',
+ 'Returns StyleX style for animating element on mount. Only animates when element dynamically inserted after initial page paint; elements rendered on page load not animated. Uses Astryx motion tokens (duration, easing) for consistent timing. Server-rendered elements hydrate without entry style, never animate; elements mounted after hydration animate.',
bestPractices: [
{ guidance: true, description: 'Use for conditionally rendered elements like validation messages, toasts, expanding sections.' },
{ guidance: true, description: 'Spread returned style into stylex.props() alongside other styles.' },
diff --git a/packages/core/src/hooks/useEntryAnimation.ssr.test.tsx b/packages/core/src/hooks/useEntryAnimation.ssr.test.tsx
new file mode 100644
index 0000000000..e4dfaeeabf
--- /dev/null
+++ b/packages/core/src/hooks/useEntryAnimation.ssr.test.tsx
@@ -0,0 +1,143 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useEntryAnimation.ssr.test.tsx
+ * @input FieldStatus server markup, React hydration, and client mounts
+ * @output Proves server-rendered entry-animated elements hydrate without mismatches
+ * @position SSR acceptance test for useEntryAnimation
+ */
+
+import {act, useState} from 'react';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {createRoot, hydrateRoot} from 'react-dom/client';
+import {renderToString} from 'react-dom/server';
+
+// Each test imports a fresh copy of FieldStatus with the hook's first-frame
+// callback held back, so server markup renders before the page "paints" (as on
+// a real server) and `paint()` then runs that frame.
+async function importFieldStatus() {
+ const frames: FrameRequestCallback[] = [];
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
+ frames.push(callback),
+ );
+ vi.resetModules();
+ const {FieldStatus} = await import('../FieldStatus');
+ vi.unstubAllGlobals();
+ const paint = () => {
+ frames.splice(0).forEach(callback => callback(performance.now()));
+ };
+ return {FieldStatus, paint};
+}
+
+function mountServerHTML(html: string): HTMLDivElement {
+ const container = document.createElement('div');
+ container.innerHTML = html;
+ document.body.appendChild(container);
+ return container;
+}
+
+function classesOf(element: Element | null): string[] {
+ return (element?.getAttribute('class') ?? '').split(/\s+/).filter(Boolean);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+describe('useEntryAnimation — SSR', () => {
+ it('hydrates server-rendered FieldStatus after the first paint without a mismatch', async () => {
+ const {FieldStatus, paint} = await importFieldStatus();
+ const tree = <FieldStatus type="error" message="x" />;
+ const serverHTML = renderToString(tree);
+ const container = mountServerHTML(serverHTML);
+ const serverClassName = container.firstElementChild?.className;
+ paint();
+
+ const consoleError = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => {});
+ const recoverableErrors: unknown[] = [];
+ let root!: ReturnType<typeof hydrateRoot>;
+ await act(async () => {
+ root = hydrateRoot(container, tree, {
+ onRecoverableError: error => recoverableErrors.push(error),
+ });
+ });
+
+ expect(
+ consoleError.mock.calls.filter(call =>
+ String(call[0] ?? '')
+ .toLowerCase()
+ .includes('hydrat'),
+ ),
+ ).toEqual([]);
+ expect(recoverableErrors).toEqual([]);
+ expect(container.firstElementChild?.className).toBe(serverClassName);
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it('still animates a client-only mount after the first paint', async () => {
+ const {FieldStatus, paint} = await importFieldStatus();
+ const staticClasses = classesOf(
+ mountServerHTML(renderToString(<FieldStatus type="error" message="x" />))
+ .firstElementChild,
+ );
+ paint();
+
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(<FieldStatus type="error" message="x" />);
+ });
+
+ const clientClasses = classesOf(container.firstElementChild);
+ expect(clientClasses).toEqual(expect.arrayContaining(staticClasses));
+ expect(clientClasses.length).toBeGreaterThan(staticClasses.length);
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it('animates a FieldStatus mounted after hydration', async () => {
+ const {FieldStatus, paint} = await importFieldStatus();
+ let showSecond!: () => void;
+ function Form() {
+ const [second, setSecond] = useState(false);
+ showSecond = () => setSecond(true);
+ return (
+ <>
+ <FieldStatus type="error" message="first" />
+ {second ? <FieldStatus type="error" message="second" /> : null}
+ </>
+ );
+ }
+ const container = mountServerHTML(renderToString(<Form />));
+ const staticClasses = classesOf(container.firstElementChild);
+ paint();
+
+ let root!: ReturnType<typeof hydrateRoot>;
+ await act(async () => {
+ root = hydrateRoot(container, <Form />);
+ });
+ await act(async () => {
+ showSecond();
+ });
+
+ const mounted = container.children[1] ?? null;
+ expect(mounted).toHaveTextContent('second');
+ const mountedClasses = classesOf(mounted);
+ expect(mountedClasses).toEqual(expect.arrayContaining(staticClasses));
+ expect(mountedClasses.length).toBeGreaterThan(staticClasses.length);
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/packages/core/src/hooks/useEntryAnimation.ts b/packages/core/src/hooks/useEntryAnimation.ts
index fcbdf9bc37..5bba2676a8 100644
--- a/packages/core/src/hooks/useEntryAnimation.ts
+++ b/packages/core/src/hooks/useEntryAnimation.ts
@@ -3,29 +3,27 @@
'use client';
/**
* @file useEntryAnimation.ts
- * @input Uses React, StyleX, theme tokens
+ * @input Uses React, StyleX, theme tokens, useIsHydrating
* @output Exports useEntryAnimation hook for mount-only entry animations
* @position Hook utility; consumed by FieldStatus and available to consumers
*
* Provides entry animations for conditionally rendered elements.
* Only animates when the element is dynamically mounted after the initial
* page paint — statically rendered elements on page load are not animated.
+ * Server-rendered elements hydrate without the entry style and never play it
+ * (spec:AST-013 FR13).
*/
import {useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {durationVars, easeVars, spacingVars} from '../theme/tokens.stylex';
+import {useIsHydrating} from './useIsHydrating';
-// Track whether the initial page paint has completed.
-// Elements rendered on page load should not animate;
-// only dynamically inserted ones should.
-//
-// NOTE: This module is marked 'use client' so it never runs on the server.
-// If the directive is removed, this flag will always be false during SSR,
-// and useState(() => initialPaintComplete) will capture false — meaning
-// animations won't run after hydration. Keep 'use client' or add an
-// effect-based fallback if SSR support is needed.
+// Track whether the initial page paint has completed, so elements a
+// client-only root renders on page load do not animate; only dynamically
+// inserted ones should. Server-rendered elements are covered by
+// useIsHydrating instead: hydration can run after this flag turns true.
let initialPaintComplete = false;
if (typeof window !== 'undefined') {
requestAnimationFrame(() => {
@@ -99,16 +97,14 @@ const styles = stylex.create({
});
export type EntryAnimationPreset =
- | 'slideDown'
- | 'slideUp'
- | 'fadeIn'
- | 'scaleIn';
+ 'slideDown' | 'slideUp' | 'fadeIn' | 'scaleIn';
/**
* Returns a StyleX style for animating an element on mount.
*
* Only animates when the element is dynamically inserted after the initial
- * page paint. Elements rendered on page load are not animated.
+ * page paint. Elements rendered on page load, including server-rendered
+ * elements while they hydrate, are not animated.
*
* @example
* ```
@@ -119,6 +115,9 @@ export type EntryAnimationPreset =
export function useEntryAnimation(
preset: EntryAnimationPreset = 'slideDown',
): StyleXStyles | null {
- const [animate] = useState(() => initialPaintComplete);
+ const isHydrating = useIsHydrating();
+ // Captured once: a hydrated element must not start animating when React
+ // re-renders it with the client snapshot after hydration.
+ const [animate] = useState(() => !isHydrating && initialPaintComplete);
return animate ? styles[preset] : null;
}
diff --git a/packages/core/src/hooks/useIsHydrating.test.tsx b/packages/core/src/hooks/useIsHydrating.test.tsx
new file mode 100644
index 0000000000..e4777ad824
--- /dev/null
+++ b/packages/core/src/hooks/useIsHydrating.test.tsx
@@ -0,0 +1,70 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useIsHydrating.test.tsx
+ * @input useIsHydrating, React server render, hydration, and client roots
+ * @output Proves the hook is true only on the server and while hydrating
+ * @position Unit test for the internal hydration-state utility
+ */
+
+import {act, useState} from 'react';
+import {afterEach, describe, expect, it} from 'vitest';
+import {createRoot, hydrateRoot} from 'react-dom/client';
+import {renderToString} from 'react-dom/server';
+import {useIsHydrating} from './useIsHydrating';
+
+const seen: boolean[] = [];
+
+function Probe() {
+ const isHydrating = useIsHydrating();
+ seen.push(isHydrating);
+ return <span data-hydrating={String(isHydrating)} />;
+}
+
+afterEach(() => {
+ seen.length = 0;
+ document.body.replaceChildren();
+});
+
+describe('useIsHydrating', () => {
+ it('is true on the server', () => {
+ expect(renderToString(<Probe />)).toContain('data-hydrating="true"');
+ });
+
+ it('is true while hydrating, then false after hydration', async () => {
+ const container = document.createElement('div');
+ container.innerHTML = renderToString(<Probe />);
+ document.body.appendChild(container);
+ seen.length = 0;
+
+ let root!: ReturnType<typeof hydrateRoot>;
+ await act(async () => {
+ root = hydrateRoot(container, <Probe />);
+ });
+
+ expect(seen[0]).toBe(true);
+ expect(seen.at(-1)).toBe(false);
+ expect(container.querySelector('span')).toHaveAttribute(
+ 'data-hydrating',
+ 'false',
+ );
+ await act(async () => root.unmount());
+ });
+
+ it('is false in a client-only root and for elements mounted after hydration', async () => {
+ let show!: () => void;
+ function Later() {
+ const [isShown, setIsShown] = useState(false);
+ show = () => setIsShown(true);
+ return isShown ? <Probe /> : null;
+ }
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ await act(async () => root.render(<Later />));
+ await act(async () => show());
+
+ expect(seen).toEqual([false]);
+ await act(async () => root.unmount());
+ });
+});
diff --git a/packages/core/src/hooks/useIsHydrating.ts b/packages/core/src/hooks/useIsHydrating.ts
new file mode 100644
index 0000000000..4433d74791
--- /dev/null
+++ b/packages/core/src/hooks/useIsHydrating.ts
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useIsHydrating.ts
+ * @input Uses React useSyncExternalStore
+ * @output Exports useIsHydrating (internal; not re-exported from hooks/index.ts)
+ * @position Internal utility; read by useEntryAnimation so markup that
+ * hydrates server HTML matches the server (spec:AST-013 FR9, FR13)
+ *
+ * React renders with the server snapshot on the server and again in the
+ * client render that hydrates server HTML, then re-renders with the client
+ * snapshot. Code that must render the server's markup while hydrating reads
+ * this instead of a first-paint flag, timer, animation frame, or mount Effect.
+ */
+
+import {useSyncExternalStore} from 'react';
+
+// Nothing ever changes, so there is nothing to subscribe to.
+const subscribe = () => () => {};
+const getSnapshot = () => false;
+const getServerSnapshot = () => true;
+
+/**
+ * Returns `true` during server render and during the client render that
+ * hydrates server HTML; `false` in every other client render.
+ */
+export function useIsHydrating(): boolean {
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
+}