[React]: Lifecycle Methods in React
React
11/05/2019
Lifecycle Method
Lifecycle methods are series of events happening from the birth of React component to its end.
You can think of it as three states:
- Mounting (Birth of component)
- Update (Growth of component)
- Unmount (Death of component)
Lifecycle diagram available from here.
Mounting
Mounting phase is when component is put on DOM for the first time. It starts before when our component is in our DOM.
It looks at the life cycle component then calls:
- constructor()
- render()
- componentDidMount()
render()
- Most used lifecycle method
- Renders JSX component to the UI
- Happens during mounting and updating phases
- render() has to return the same output when same inputs are passed
- i.e. don't put setState() in render(). You shouldn't change the state in render().
componentDidMount()
- Gets called right after component is mounted
- Good place to start API calls to load the data
- Allows setState() which update state and render(), but it happens before browser updates the UI, so that viewer can't see undesired UI updates.
- Ensure that states are assigned in the constructor()
- Use of setState() in here is to allow special cases: tooltips, modals, etc
Updating
componentDidUpdate()
Invoked right after update happens. This updates DOM based on state/prop change.
setState() is allowed but pass in prevProps to prevent infinite loop.
componentDidUpdate(prevProps) { if (this.props.data !== prev.Props.data) this.fetchData(this.props.data);}
This ensures not to make API call when there props did not change.
shouldComponentUpdate()
Called when you want React not to re-render for particular state/prop changes.
Should only be used for optimizing performance.
When returns false, it discontinues the lifecycle methods.
Unmounting
componentWillUnmount()
Called right before component gets destroyed. This is a good place to do clean ups to prevent memory leak.
You can't modify state here.