React Component Lifecycle Methods Cheatsheet
Bunlong
Posted on February 2, 2020
Each component in React has a lifecycle which you can monitor and manipulate.
Lifecycle Explanation:
- Mounting: Called before your component is displayed on the UI.
- Updating: Caused by a change to props or state and rerendered the UI.
- Unmounting: Called when your UI will no longer display the component.
Mounting
constructor
- Lifecycle: Mount immediately before render.
- Purpose: Initialize state.
// Commonly Used Lifecycle Methods
constructor() {
}
componentDidMount
- Lifecycle: Mount immediately after render.
- Purpose: Initialize state that requires DOM nodes, Network requests and side effects.
componentDidMount() {
}
Updating
shouldComponentUpdate
- Lifecycle: Update immediately before render.
- Purpose: Allows developer to prevent rendering.
shouldComponentUpdate(nextProps, nextState) { // Optional Parameters
}
render
Code to display the component.
// Required
render() {
}
getSnapshotBeforeUpdate
- Lifecycle: Update immediately before render output is committed to DOM.
- Purpose: Capture DOM information such as scroll position which could change.
getSnapshotBeforeUpdate(prevProps, prevState) { // Optional Parameters
}
componentDidUpdate
- Lifecycle: Update immediately after render.
- Purpose: Operate on updated DOM or handle network requests.
componentDidUpdate(prevProps, prevState, snapshot) { // Optional Parameters
}
Mounting & Updating
getDerivedStateFromProps
- Lifecycle: Mount and update immediately before render.
- Purpose: When your state depends on props (should be avoided).
// Rarely Used Lifecycle Methods
static getDerivedStateFromProps(props, state) { // Optional Parameters
}
Unmounting
componentWillUnmount
- Lifecycle: Unmount.
- Purpose: Clean up things such as event handlers, cancel network request, etc.
componentWillUnmount() {
}
Other Methods
componentDidCatch
Creates an error boundary to captures errors from child components.
// Special Use Cases
componentDidCatch(error, info) { // Optional Parameters
}
References
💖 💪 🙅 🚩
Bunlong
Posted on February 2, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How to build a website using React and Rest APIs (React basics explained)
November 6, 2024