iTwin / iTwinUI

A design system for building beautiful and well-working web interfaces.
https://itwin.github.io/iTwinUI/
MIT License
92 stars 35 forks source link

add `useHydration` check for ShadowRoot #1962

Closed mayank99 closed 1 month ago

mayank99 commented 1 month ago

Changes

This PR adds a new useHydration hook to help determine hydration state, which is then used in VisuallyHidden and ShadowRoot to prevent unnecessary null renders on client. (Follow-up to #1936, #1954, #1956, for #1930)

To make the hydration state available everywhere without re-running the same code over and over, HydrationProvider is used. useHydration will reuse the context value if the code has already executed. This optimization is also useful when the server render only happens for a small part of the application (e.g. initial page / loading state), and then every subsequent navigation happens entirely on client.

The implementation itself relies on useSyncExternalStore to determine "hydrating" state (see getServerSnapshot docs) and useEffect to determine "hydrated" state (see useEffect docs).

Testing

Tested ProgressRadial and VisuallyHidden in playgrounds:

Also tested that React 17 is functional (see commit). I did get a hydration warning in Nextjs, but no serious errors.

Made sure all existing tests pass.

Docs

N/A

Added changeset to briefly mention the overall effect on users.