# React-Lifecycle-Cheatsheet Short reference of React.Component lifecycle methods so I don't have to scroll through the huge text on the official documentation ![Lifecycle Diagram](./Lifecycle-chart.jpg) ## Mounting #### constructor () ```js /** * Create state and call super * * @param {object} props */ constructor (props) { super(props); this.state = { foo: 'bar' } } ``` #### static getDerivedStateFromProps () ```js /** * Props have changed, return the updated state * * @param {object} nextProps - Props for the next render * @param {object} prevState - State from previous render * @return {object | null} - The change to the state */ static getDerivedStateFromProps (nextProps, prevState) { // Nothing to update return null; // Set new state return { foo: 'foobar' }; } ``` #### componentDidMount () ```js /** * Component mounted, will render soon */ componentDidMount () { // Network calls, state changes, // anything is fair game here } ``` ## Updating #### shouldComponentUpdate () ```js /** * Hook to control re-render * * @param {object} nextProps * @param {object} nextState * @return {boolean} - Whether to render this cycle */ shouldComponentUpdate (nextProps, nextState) { // Default in React.Component return true; // React.PureComponent implements this method // with a shallow compare of props and state } ``` #### render () ```js /** * Render returned components * * @return {React Element | string | number | Portal | null | boolean} */ render () { return
; } ``` #### getSnapshotBeforeUpdate () ```js getSnapshotBeforeUpdate (prevProps, prevState) { } ``` #### componentDidUpdate () ```js componentDidUpdate (prevProps, prevState, snapshot = undefined) { } ``` ## Unmounting #### componentWillUnmount () ```js componentWillUnMount () { // Cleanup whatever you need to before the // component unmounts } ``` --- ## Deprecated ### UNSAFE_componentWillMount () ### UNSAFE_componentWillReceiveProps () ### UNSAFE_componentWillUpdate ()