HOC to add lifecycle hooks to any component, even stateless ones.
Install via npm:
npm install react-with-lifecycleimport and wrap your components with a lifecycle object:
importWithLifecyclefrom'react-with-lifecycle';constWidgetList=({ widgets, loading })=>(<div>{loading&&'Loading widgets...'}{!loading&&widgets.map(widget=><spankey={widget.id}>{widget.name}</span>)}</div>);exportdefaultWithLifecycle({componentDidMount({ loadWidgets }){loadWidgets();}},WidgetList)In a redux app, this is a useful pattern for building containers:
import{connect}from'react-redux';import{bindActionCreators}from'redux';import{loadWidgets}from'actions/WidgetsActions';importWidgetListfrom'components/WidgetList';importWithLifecyclefrom'react-with-lifecycle';// ...connect(mapStateToProps,dispatch=>bindActionCreators({ loadWidgets },dispatch))(WithLifecycle({componentDidMount({ loadWidgets }){loadWidgets();}},WidgetList));Lifecycle methods are called with arguments of props, state, and ...arguments, where arguments are the original parameters passed into the lifecycle method by react. This allows access to the standard arguments called by each lifecycle method:
WithLifecycle({componentDidUpdate(props,state,prevProps,prevState){// ...}},WidgetList));