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

Fix redundant set state in useResizeDetector #121

Closed lukesmurray closed 3 years ago

lukesmurray commented 3 years ago

When you call setState with an object that is deeply equal to the current state you trigger a render even though the state has not changed.

The current useResizeDetector renders the component it is attached to at the refreshRate. This is not good for performance.

In order to fix the issue we should not change the size state unnecessarily. I changed the setSize call in the createAsyncNotifier to check the current width and height. If the width and height are the same we return the current state. We only update the state if the width and height change.

I also had to change the setSize type definition to enable using the function form of setState.

See this link for more information about redundant rerenders caused by hooks.

maslianok commented 3 years ago

@lukesmurray looks great! Thank you 👍

one tiny improvement and I'll merge it

maslianok commented 3 years ago

Merged.

Published v6.1.0