Skip to content

Instantly share code, notes, and snippets.

@velotiotech
Created June 25, 2020 12:40
Show Gist options
  • Save velotiotech/a1dff9ce781015f2a7e274529080f8ed to your computer and use it in GitHub Desktop.
Save velotiotech/a1dff9ce781015f2a7e274529080f8ed to your computer and use it in GitHub Desktop.
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