Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Created August 6, 2018 17:07
Show Gist options
  • Save treyhuffine/614cb7d48191a208c756725d382c55cd to your computer and use it in GitHub Desktop.
Save treyhuffine/614cb7d48191a208c756725d382c55cd to your computer and use it in GitHub Desktop.
A summary of the React 16 lifecycle methods
class ComponentWithLifecycle extends React.Component {
// Commonly Used Lifecycle Methods
constructor() {
- Lifecycle: Mounting (before render)
- Purpose: Initialize state
}
componentDidMount() {
- Lifecycle: Mounting (immediately after render)
- Purpose: Initialize state that requires DOM nodes,
Network requests and side effects
}
componentDidUpdate() {
- Lifecycle: Updating (immediately after update)
- Purpose: Operate on updated DOM or handle network requests
}
componentWillUnmount() {
- Lifecycle: Unmounting
- Purpose: Clean up things such as event handlers, cancel network requests, etc
}
// Rarely Used Lifecycle Methods
static getDerivedStateFromProps() {
- Lifecycle: Mounting and Updating (immediately before render)
- Purpose: When your state depends on props (should be avoided)
}
shouldComponentUpdate() {
- Lifecycle: Updating (immediately before render), return boolean
- Purpose: Allows developer to prevent rendering
}
getSnapshotBeforeUpdate() {
- Lifecycle: Updating (immediately before render output is committed to DOM)
- Purpose: Capture DOM information such as scroll position which could change
}
// Special Use Cases
componentDidCatch() {
- Creates an error boundary to captures errors from child components
}
// Required
render() {
- Code to display the component
}
}
Lifecycle Explanation:
- Mounting: Called before your component is displayed on the UI
- Updating: Caused by a change to props or state and rerenders the UI
- Unmounting: Called when your UI will no longer display the component
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment