jaredLunde / jaredLunde/react-hook
The useSize() demo for resize-observer doesn't capture element's initial size
- Dominant language
- TypeScript
- Stars
- 1.5k
- Forks
- 96
- PR merge metrics
- No merged PRs in 30d
Description
**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
```ts
export function useSize(): {
ref: (node: HTMLDivElement | null) => void
size: DOMRect | undefined
} {
const [size, setSize] = useState()
const [node, ref] = useState(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
}
```
Contributor guide
Research direction
Find the resize-observer demo and inspect its useSize() hook, especially the useLayoutEffect dependency and useResizeObserver(node) entry point. Verify how the demo behaves on an element that does not re-render, then ensure the initial size is captured on first render and confirm the displayed size is correct.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- react, typescript
- Domain
- frontend
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100