Lifecycle of React components

 What I learned today: how to use lifecycle of React components without using class


When we talk about the lifecycle of react components, we are talking about

Mounting

Unmounting

Updating

The reason it is important to understand is because there are side effects that we need to perform during the lifecycle of a component such as api calls, initialization, and cleanups(release resources like event listeners).


1) mounting - when a component is first is injected into the DOM and rendered for the first time

2) unmounting - when a component is removed from the DOM and is no longer being rendered

3) Updating - when a state inside the component changes or prop is passed into the component


The useEffect hook is useful and can run in all of these different lifecycles.

import { useEffect } from 'react'

The basic syntax takes in a callback function:

useEffect(()=>{
  //code
})

this will run everytime a component mounts or updates.

In order to run only when the component mounts:

useEffect(()=>{
  //code
}, [])

To run when a component update a state or receives a prop:

useEffect(()=>{
  //code
}, [stateVariable])

and to run when a component unmounts:

useEffect(()=>{
  return () => {
  //code
  }
}, [])





Comments

Popular posts from this blog

Styled Components

e-commerce website built with React.nodejs