Skip to content

Commit 7324d03

Browse files
Jessidhiafouad
authored andcommitted
Use proper inputs, fix ResizeObserver setup
Declares the proper inputs to register/deregister the layout effect. I'm not sure if the `ref` parameter should be expected to change ever (rules of hooks) but use it when generating the callback too. Also fixes incorrect ResizeObserver `.observe` call if the `ref` was not initialized on initial render (maybe it's in an element that's conditionally rendered).
1 parent f4a3dc9 commit 7324d03

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

index.js

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
'use strict'
2-
let { useState, useLayoutEffect } = require('react')
2+
let { useCallback, useState, useLayoutEffect } = require('react')
33

44
function getSize(el) {
55
if (!el) {
@@ -15,13 +15,18 @@ function getSize(el) {
1515
function useComponentSize(ref) {
1616
let [ComponentSize, setComponentSize] = useState(getSize(ref.current))
1717

18-
function handleResize() {
19-
if (ref && ref.current) {
20-
setComponentSize(getSize(ref.current))
21-
}
22-
}
18+
const handleResize = useCallback(
19+
function handleResize() {
20+
if (ref.current) {
21+
setComponentSize(getSize(ref.current))
22+
}
23+
},
24+
[ref]
25+
)
2326

2427
useLayoutEffect(() => {
28+
if (!ref.current) { return }
29+
2530
handleResize()
2631

2732
if (ResizeObserver) {
@@ -40,7 +45,7 @@ function useComponentSize(ref) {
4045
}
4146
}
4247

43-
}, [])
48+
}, [ref.current])
4449

4550
return ComponentSize
4651
}

0 commit comments

Comments
 (0)