react-use icon indicating copy to clipboard operation
react-use copied to clipboard

useWindowSize callback

Open amcdnl opened this issue 5 years ago • 5 comments

Add ability to trigger a callback when the size is updated.

const { ... } = useWindowSize(() => {
...callback on resize...
});

amcdnl avatar Jan 21 '20 15:01 amcdnl

Keen to take this on 😄

  1. Is there anything useful which we would want to return?
  2. Would another arg to control debouncing be useful or should we leave that to the user to handle?
  3. Would it be useful to pass current height/width to the callback or do we leave this to the user as well?

morgsmccauley avatar Jan 27 '20 22:01 morgsmccauley

@morgsmccauley great, its all yours!

Is there anything useful which we would want to return?

Would be useful to return its state, i.e {width, height}.

Would another arg to control debouncing be useful or should we leave that to the user to handle?

Maybe we can use useRafState.

streamich avatar Jan 27 '20 22:01 streamich

I'll try draft something up 👍

morgsmccauley avatar Jan 28 '20 06:01 morgsmccauley

Just trying to understand things a little more:

  • What is the use case here? useWindowSize triggers a re-render with the latest width/height. Wouldn't using these values in the component achieve the same thing as a callback?

  • I think i've landed on exposing a callback arg from useRafState so that useWindowSize can leverage this to trigger before next re-paint. Is this along the lines of what you had in mind?

Will appreciate any answers to these! 😄

morgsmccauley avatar Feb 03 '20 08:02 morgsmccauley

What is the use case here?

If you want to do something with the window size, like some side-effect of pass the state to parent component, now you have to use useWindowSize together with useEffect:

const {width, height} = useWindowSize();
useEffect(() => {
  // ...
}, [width, height]);

with a callback it would be more direct:

const {width, height} = useWindowSize({
  onChange: (width, height) => {
    // ...
  },
});

Is this along the lines of what you had in mind?

Would need to see the code for that.

streamich avatar Feb 03 '20 22:02 streamich