-
Notifications
You must be signed in to change notification settings - Fork 2.2k
useGridDimensions: useSyncExternalStore implementation #3968
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
Changes from all commits
1f1bd62
5a25695
1c32fe5
9e2ddd5
0617759
f5623d4
a9c35e5
65fef94
4b7952b
72fbfe1
26ad3ad
5560676
56ece28
cae48cf
b78a048
772dafc
e6d1977
4625957
278e419
ed656fe
b196840
93ef101
e202100
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,39 +1,85 @@ | ||
| import { useLayoutEffect, useState } from 'react'; | ||
| import { flushSync } from 'react-dom'; | ||
| import { useCallback, useLayoutEffect, useSyncExternalStore, type RefObject } from 'react'; | ||
|
|
||
| export function useGridDimensions({ | ||
| gridRef | ||
| }: { | ||
| gridRef: React.RefObject<HTMLDivElement | null>; | ||
| }) { | ||
| const [inlineSize, setInlineSize] = useState(1); | ||
| const [blockSize, setBlockSize] = useState(1); | ||
| const initialSize: ResizeObserverSize = { | ||
| inlineSize: 1, | ||
| blockSize: 1 | ||
| }; | ||
|
|
||
| useLayoutEffect(() => { | ||
| const { ResizeObserver } = window; | ||
| // use an unmanaged WeakMap so we preserve the cache even when | ||
| // the component partially unmounts via Suspense or Activity | ||
| const sizeMap = new WeakMap<RefObject<HTMLDivElement | null>, ResizeObserverSize>(); | ||
| const targetToRefMap = new WeakMap<HTMLDivElement, RefObject<HTMLDivElement | null>>(); | ||
| const subscribers = new Map<RefObject<HTMLDivElement | null>, () => void>(); | ||
|
|
||
| // don't break in Node.js (SSR), jsdom, and environments that don't support ResizeObserver | ||
| const resizeObserver = | ||
| // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | ||
| globalThis.ResizeObserver == null ? null : new ResizeObserver(resizeObserverCallback); | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We'll have 1 RO instance for all rendered grids on the page, so all resize events will be batched together -> improved perf? |
||
|
|
||
| function resizeObserverCallback(entries: ResizeObserverEntry[]) { | ||
| for (const entry of entries) { | ||
| const target = entry.target as HTMLDivElement; | ||
|
|
||
| if (targetToRefMap.has(target)) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is it worth removing this map and just looping through
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TIL
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yup, it's because weak references cannot be held strongly -> cannot find all the weak references -> cannot iterate through them |
||
| const ref = targetToRefMap.get(target)!; | ||
| updateSize(ref, entry.contentBoxSize[0]); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| function updateSize(ref: RefObject<HTMLDivElement | null>, size: ResizeObserverSize) { | ||
| if (sizeMap.has(ref)) { | ||
| const prevSize = sizeMap.get(ref)!; | ||
| if (prevSize.inlineSize === size.inlineSize && prevSize.blockSize === size.blockSize) { | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| sizeMap.set(ref, size); | ||
| subscribers.get(ref)?.(); | ||
| } | ||
|
|
||
| function getServerSnapshot(): ResizeObserverSize { | ||
| return initialSize; | ||
| } | ||
|
|
||
| // don't break in Node.js (SSR), jsdom, and browsers that don't support ResizeObserver | ||
| // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition | ||
| if (ResizeObserver == null) return; | ||
| export function useGridDimensions(gridRef: React.RefObject<HTMLDivElement | null>) { | ||
| const subscribe = useCallback( | ||
| (onStoreChange: () => void) => { | ||
| subscribers.set(gridRef, onStoreChange); | ||
|
|
||
| const { clientWidth, clientHeight } = gridRef.current!; | ||
| return () => { | ||
| subscribers.delete(gridRef); | ||
| }; | ||
| }, | ||
| [gridRef] | ||
| ); | ||
|
|
||
| setInlineSize(clientWidth); | ||
| setBlockSize(clientHeight); | ||
| const getSnapshot = useCallback((): ResizeObserverSize => { | ||
| // ref.current is null during the initial render, when suspending, or in <Activity mode="hidden">. | ||
| // We use ref as key instead to access stable values regardless of rendering state. | ||
| return sizeMap.get(gridRef) ?? initialSize; | ||
| }, [gridRef]); | ||
|
|
||
| // We use `useSyncExternalStore` instead of `useState` to avoid tearing, | ||
| // which can lead to flashing scrollbars. | ||
| const { inlineSize, blockSize } = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); | ||
|
|
||
| useLayoutEffect(() => { | ||
| const target = gridRef.current!; | ||
|
|
||
| const resizeObserver = new ResizeObserver((entries) => { | ||
| const size = entries[0].contentBoxSize[0]; | ||
| targetToRefMap.set(target, gridRef); | ||
| resizeObserver?.observe(target); | ||
|
|
||
| // we use flushSync here to avoid flashing scrollbars | ||
| flushSync(() => { | ||
| setInlineSize(size.inlineSize); | ||
| setBlockSize(size.blockSize); | ||
| if (!sizeMap.has(gridRef)) { | ||
| updateSize(gridRef, { | ||
| inlineSize: target.clientWidth, | ||
| blockSize: target.clientHeight | ||
| }); | ||
| }); | ||
| resizeObserver.observe(gridRef.current!); | ||
| } | ||
|
|
||
| return () => { | ||
| resizeObserver.disconnect(); | ||
| resizeObserver?.unobserve(target); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should we call
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Mmh, in general I'd not manage WeakMaps too much, that way if the code becomes more complicated we won't run into an bug where we expect the mapping to still exist. FYI layout effects will clean up when suspending or when it's under |
||
| }; | ||
| }, [gridRef]); | ||
|
|
||
|
|
||

There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I took great care to ensure this works great even if the components unmounts but the div isn't deleted.
The updated hook is more complicated than before, but should behave great with concurrent rendering ✌️