Skip to content

Commit a67f34e

Browse files
committed
Addresses debouncing for resize events at 50ms
This directly addresses #2, where debounce is needed for resize. Without a debounce, `this.handleResize()` is called hundreds of times during a resize operation, potentially causing multiple prop changes, and multiple renders. The debounce used is based on underscore and jQuery's debounce, without the `immediate` flag. Debounce was set to 50ms, which is a reasonable default. I don't personally think it needs to be configurable, it just needed to be debounced.
1 parent 8ff3745 commit a67f34e

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/withBreakpoints.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,20 @@ import airbnbBreakpoints from '../util/airbnb-breakpoints';
44

55
const Context = React.createContext();
66

7+
// debouncing function for kristof0425/react-with-breakpoints/29
8+
const debounce = (func, interval) => {
9+
let timeout;
10+
return (...args) => {
11+
const context = this;
12+
let later = () => {
13+
timeout = null;
14+
func.apply(context, args);
15+
}
16+
clearTimeout(timeout);
17+
timeout = setTimeout(later, interval);
18+
};
19+
};
20+
721
export const withBreakpoints = (WrappedComponent) => {
822
const Component = (props) => (
923
<Context.Consumer>
@@ -45,7 +59,8 @@ export default class BreakpointsProvider extends PureComponent {
4559
}
4660

4761
componentDidMount() {
48-
window.addEventListener('resize', this.handleResize, { passive: true });
62+
const debouncedResize = debounce(this.handleResize, 50);
63+
window.addEventListener('resize', debouncedResize, { passive: true });
4964
this.handleResize();
5065
}
5166

0 commit comments

Comments
 (0)