maslianok / react-resize-detector

A Cross-Browser, Event-based, Element Resize Detection for React
http://maslianok.github.io/react-resize-detector/
MIT License
1.25k stars 91 forks source link

Potential issue: `onResize` behave differently between child function patter and hook #126

Closed akphi closed 3 years ago

akphi commented 3 years ago

Consider the following scenarios. When the value of editor is updated, the hooks form won't allow you to use another version of onResize with editor !== null. This also appears to be the case for handleWidth and handleHeight.

import ResizeDetector, { useResizeDetector } from 'react-resize-detector';

// Hooks form (v6)
function App() {
  const [editor, setEditor] = useState(null);

  const { ref } = useResizeDetector({
    handleWidth: true,
    handleHeight: true,
    onResize: (width, height) => {
      editor?.something(width, height) // editor is always null here no matter if it's set to some other values by `setEditor`
    },
  });

  return (
    <div ref={ref}>MyComponent</div>
  );
}

// Child function pattern
function App() {
  const [editor, setEditor] = useState(null);

  return (
    <ResizeDetector
      handleHeight={true}
      handleWidth={true}
      onResize={(width, height) => {
        editor?.something(width, height) // `editor` value will be updated here
      }}
    >
      <div>MyComponent</div>
    </ResizeDetector>
  );
}

I guess the workaround for onResize is to use useEffect with the value of height and width returned from useResizeDetector(). But the fact that handleWidth and handleHeight cannot be dynamic makes it hard for me to try out hooks form šŸ˜­

maslianok commented 3 years ago

Thanks for reporting the issue!

Should be fixed in v6.3.0

akphi commented 3 years ago

@maslianok Thank you!! I will check it later. I think we accidentally left a 'console.log' in the code for useResizeDetector though šŸ˜… Submitted a PR to save you some time.

maslianok commented 3 years ago

someday I won't forget about console.logs... someday... šŸ˜„

Thanks for the PR. Published in 6.3.1 :)