top of page
Logo der Online Agentur mdwp

Lifecycle Methods

React.js Lifecycle Methods are specifically built-in methods in the React library that get called at different stages of a component's life in a React application.

In simple words, They are the series of events that happen from the birth of a React component to its death.

Lifecycle methods can be divided into three different phases:

1. Mounting (Component being put into the DOM)
2. Updating (Component is being re-rendered as a result of changes to either its props or state)
3. Unmounting (Component being removed from the DOM)

A few common lifecycle methods are:

1. componentWillMount: Executed before rendering.
2. componentDidMount: Executed after the first render.
3. componentDidUpdate: Executed after the initial rendering when there are changes in the state or the props.
4. componentWillUnmount: Executed just before the component is unmounted from the DOM.

Every component in React has a lifecycle which you can monitor and manipulate during each phase.

Here's simple code snippet:

class ExampleComponent extends React.Component {
this.state = {example: true};

componentWillMount() {
//Executed before rendering.

//Executed after the first render

componentDidUpdate(prevProps, prevState) {
//Executed after the re-render

//Executed just before the component is unmounted from the DOM.

render() {
return (
Example Component
In the above example 'componentWillMount', 'componentDidMount', 'componentDidUpdate', and 'componentWillUnmount' lifecycle methods are used.

These lifecycle methods have varied uses, for example, fetching data from an API is typically done in the 'componentDidMount' lifecycle method while any cleanup, like invalidating timers or cancelling API requests, is performed in the 'componentWillUnmount' lifecycle method.

bottom of page