I would like to have my components behave differently depending on the width of the browser window.
Instead of repeating the same functions for getting the width of the browser in every component, I am considering wrapping all components in a parent component -
<mainComponent>
<childComponent1/>
<childComponent2/>
<.../>
</mainComponent>
which gets the width of the window and passes it to the child components -
handleResize = (e) => {
this.setState({windowWidth: window.innerWidth})
};
componentWillMount() {
this.handleResize()
}
componentDidMount() {
window.addEventListener('resize', this.handleResize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize)
}
render() {
return <div>
{React.cloneElement(this.props.children, { windowWidth: this.state.windowWidth })}
</div>
}
This seems like a bad solution as it may negatively impact performance, especially if the application becomes large.
- Am I right to assume that there would be a performance problem with this solution?
- During a resize event, the prop value passed to the child changes continuously during the resize action (725, 724, 723, ...). Would there be any performance gains if the width is grouped (s, m, l, xl, ...) so that the props passed to the child does not change as often?
- It may become easier to manage state if I use something like Redux or Relay, but would there be any performance gain?
- Is there a better way to solve this problem from a performance perspective?