ZeeCoder / use-resize-observer

A React hook that allows you to use a ResizeObserver to measure an element's size.
MIT License
644 stars 42 forks source link

No values reported when using React StrictMode #90

Closed fabianishere closed 2 years ago

fabianishere commented 2 years ago

Hi,

I am using this hook in one of my projects in conjunction with React 18 and Strict Mode. However, it appears that the hook does not report any values when used together with React Strict Mode.

See the following CodeSandbox for a demonstration of this issue.

This issue is caused by the fact that React Strict Mode renders components twice in development mode in order to detect problems. In particular, this behavior causes problems with the following logic (for tracking unmounts):

https://github.com/ZeeCoder/use-resize-observer/blob/653b0b98d5614b083835880736555b79536326aa/src/index.ts#L196-L200

Because the component is rendered twice, the component is marked as unmounted and no further size updates are reported by the hook.

I believe the following patch should resolve this issue:

  const didUnmount = useRef(false);
  useEffect(() => {
+   didUnmount.current = false;
    return () => {
      didUnmount.current = true;
    };
  }, []);
ZeeCoder commented 2 years ago

Thank you for the reproduction and the detailed report. :pray: I plan to do a release soon, just have to update the tests so that they run for at least React 17 and 18 to ensure compatibility.

fabianishere commented 2 years ago

Awesome, let me know if I can be of any help :)

SawasReaper commented 2 years ago

Any update on that one? ^^ 🙏

ZeeCoder commented 2 years ago

Hopefully I'll have some time this weekend to wrap things up :crossed_fingers:

github-actions[bot] commented 2 years ago

:tada: This issue has been resolved in version 9.0.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket: