Skip to content

Instantly share code, notes, and snippets.

@fmo91
Created March 28, 2018 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmo91/10343842fcd93792e1dc464881ea9c1a to your computer and use it in GitHub Desktop.
Save fmo91/10343842fcd93792e1dc464881ea9c1a to your computer and use it in GitHub Desktop.
React HOC that logs debug messages on lifecycle methods
import React, { Component } from 'react';
const { log } = console;
export default (prefix) => (WrappedComponent) => {
const message = text => `[${prefix}] ${text}`;
return class EnhancedComponent extends WrappedComponent {
render() {
log(message("render()"));
return super.render();
}
constructor(props) {
super(props);
log(message("constructor(props)"), props);
}
componentWillMount() {
super.componentWillMount && super.componentWillMount();
log(message("componentWillMount()"));
}
componentDidMount() {
super.componentDidMount && super.componentDidMount();
log(message("componentDidMount()"));
}
componentWillReceiveProps(nextProps) {
super.componentWillReceiveProps && super.componentWillReceiveProps(nextProps);
log(message("componentWillReceiveProps(nextProps)"), nextProps);
}
shouldComponentUpdate(nextProps, nextState) {
log(message("shouldComponentUpdate(nextProps, nextState)"), nextProps, nextState);
if (super.shouldComponentUpdate) {
return super.shouldComponentUpdate(nextProps, nextState);
} else {
return true;
}
}
componentWillUpdate(nextProps, nextState) {
super.componentWillUpdate && super.componentWillUpdate(nextProps, nextState);
log(message("componentWillUpdate(nextProps, nextState)"), nextProps, nextState);
}
componentDidUpdate(prevProps, prevState) {
super.componentDidUpdate && super.componentDidUpdate(prevProps, prevState);
log(message("componentDidUpdate(prevProps, prevState)"), prevProps, prevState);
}
componentWillUnmount() {
super.componentWillUnmount && super.componentWillUnmount();
log(message("componentWillUnmount()"));
}
componentDidCatch(error, info) {
super.componentDidCatch && super.componentDidCatch(error, info);
log(message("componentDidCatch(error, info)"), error, info);
}
};
};
@fmo91
Copy link
Author

fmo91 commented Mar 28, 2018

Usage

@withLifecycleDebug("AComponent")
export default class AComponent extends React.Component {
    // ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment