Created
March 28, 2018 15:53
-
-
Save fmo91/10343842fcd93792e1dc464881ea9c1a to your computer and use it in GitHub Desktop.
React HOC that logs debug messages on lifecycle methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage