Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

useEffect

 useEffect are used to perform side effects operations in functional


components.
 It acts as a alternate for comopnentDidMount( ),
componentDidUpdate( ), componentWillUnmount( )
 useEffect accepts 2 arguments.
Syntax

useEffect( < functions >, < dependency >)

It can be an asynchronous This array of dependency tells


function. when to re-run the effect.

Performs asynchronous operations It is optional.


like data fetching inside it.

App.jsx
import React from 'react'
import { useState } from 'react'
import { useEffect } from 'react'
import Nav from './Nav'

const App = () => {

let [dish,setDish]=useState("dosa")

useEffect(() => {
console.log("render method");
})

//!empty dependency--->componentDidMount
useEffect(() => {
console.log("Component mounting");
}, [])

//!componentDidUpdate
useEffect(() => {
console.log("update");
},[dish])

let changeDosa = () => {


setDish("Dahibara")
}
return (
<>
<h1>{dish}</h1>
<button onClick={changeDosa}>Change the dish</button>
</>
)
}

export default App

Ex: unmounting
App.jsx
import React from 'react'
import { useState } from 'react'
import { useEffect } from 'react'
import Nav from './Nav'

const App = () => {

let [dish,setDish]=useState("dosa")

useEffect(() => {
console.log("render method");
})
//!empty dependency--->componentDidMount
useEffect(() => {
console.log("Component mounting");
}, [])

//!componentDidUpdate
useEffect(() => {
console.log("update");
},[dish])

let changeDosa = () => {


setDish("Dahibara")
}
return (
<>
<h1>{dish==="dosa"?<Nav/>:<></>}</h1>
<button onClick={changeDosa}>Change the dish</button>
</>
)
}

export default App

Nav.jsx
import React, { useEffect } from 'react'

const Nav = () => {


//!componentwillumount--->cleanup function

useEffect(() => {
return () => {
console.log("umounting");
}
})

return (
<div>Unmounting Example</div>
)
}

export default Nav


Ex:equivalent to render

EX: componentDidUpdate

You might also like