Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cleaner Efficient Code with Hooks and Functional Programming - Wrapper Hell issue - Media component using render props
import React from "react";
export default class Media extends React.Component {
removeListener = () => null;
constructor(props) {
super(props);
this.state = {
matches: window.matchMedia(this.props.query).matches
};
}
componentDidMount() {
this.init();
}
init() {
const media = window.matchMedia(this.props.query);
if (media.matches !== this.state.matches) {
this.setState({ matches: media.matches });
}
const listener = () => this.setState({ matches: media.matches });
media.addListener(listener);
this.removeListener = () => media.removeListener(listener);
}
componentDidUpdate(prevProps) {
if (prevProps.query !== this.props.query) {
this.removeListener();
this.init();
}
}
componentWillUnmount() {
this.removeListener();
}
render() {
return this.props.children(this.state.matches);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment