React JS Lifecycle methods for class component
react

React JS Lifecycle methods for class component

https://github.com/emuroiwa/react-concepts/tree/master/src/components/Lifecycle

When a React JS (we should find a short way to write this) component is created it goes through several stages of its lifecycle, React gives us methods we can override. These are the stages below. These methods are for a class component

Mounting

Methods called when a component is created inserted into the dom

constructor, static getDerivedStateFromProps, render, componentDidMount

Updating

Methods called when a component is re-rendering due to changes in props or state

static getDerivedStateFromProps, shouldComponentUpdate, render getSnapshotBeforeUpdate and componentDidUpdate

Unmounting

Methods called when a component is being removed from the DOM

componentWillUnmount

Error Handling

Methods called when there is an error in the component or child component

static getDerivedStateFromError and componentDidCatch

Mounting Phase Methods

We will be listing them in the order of execution.

constructor( props )

  • A function that is called when a component is created
  • Initializing state and binding event handlers
  • super(props)

static getDerivedStateFromProps( props, state )

React docs say this you rarely get to use unless when the state of a component depends on props over time

render()

reads state and props

componentDidMount()

The method is run when the parent and children are rendered to the DOM. Best place to run your HTTP requests

Updating Phase Methods

We will be listing them in the order of execution.

static getDerivedStateFromProps( props, state )

Called when the component is rendered

shouldComponentUpdate( nextProps, nextState )

Used for performance optimization check, dictates whether component should be rendered or not. It returns true or false

render()

The only required method, read state and props and renders JSX. Don’t make HTTP requests or change the DOM

getSnapshotBeforeUpdate( prevProps, prevState )

Called before the changes from the Virtual DOM are reflected in the DOM. Captures info from the DOM. Returns a value or NULL

componentDidUpdate( prevProps, prevState, snapshot )

You can do HTTP calls. Called after render to check if parent and child components have properly re-rendered.

Unmount Phase Methods

componentWillUnmount()

The method called immediately before a component is mounted and destroyed. Uses below

  • cancelling and network requests
  • cancelling any subscriptions
  • invalidating timers

Error Handling Phase Methods

static getDerivedStateFromError( error )

componentDidCatch( error, info )

Leave a Reply

Close Menu