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

The useSize() demo for resize-observer doesn't capture element's initial size #165

Open
jdthorpe opened this issue Nov 21, 2021 · 1 comment
Labels
good first issue Good for newcomers

Comments

@jdthorpe
Copy link

Describe the bug
The useSize() function in the demo for @react-hook/resize-observer uses the anti-pattern of depending on the ref object provided by React.useRef() in the dependency list of React.useLayoutEffect(). This has the effect of not setting an initial value for the size on the first rendering. This matters because elements that don't get re-rendered never get a sized.

To Reproduce
Use the size

Expected behavior
Get a size for elements on the first time they are rendered.

Additional context
Depending on the node itself via useState instead of the ref (which is never updated and therefor never calls) is the usual work around

export function useSize(): {
    ref: (node: HTMLDivElement | null) => void
    size: DOMRect | undefined
} {
    const [size, setSize] = useState<DOMRect | undefined>()
    const [node, ref] = useState<HTMLElement | null>(null)

    useLayoutEffect(() => {
        node !== null && setSize(node.getBoundingClientRect())
    }, [node])

    // Where the magic happens
    useResizeObserver(node, (entry) => {
        setSize(entry.contentRect)
    })

    return { ref, size } // this is also a little wierd since ref isn't a ref object but a setter function, but works if using it in the context of <div ref={ref}>
}
@jdthorpe jdthorpe changed the title The useSize() deom for resize-observer doesn't work for elements whose size doesn't change The useSize() demo for resize-observer doesn't capture element's initial size Nov 21, 2021
@jaredLunde
Copy link
Owner

https://codesandbox.io/s/react-hookresize-observer-example-ft88x?file=/src/App.js

Fixed in the demo but feel free to submit a PR for the README :) Thanks!

@jaredLunde jaredLunde added the good first issue Good for newcomers label Nov 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

2 participants