Sunday, 22 September 2024

React Hooks - useEffect

Ø The useEffect Hook allows you to perform side effect in your components. 

Ø Side effects include fetching data, directly updating the DOM and timers like setTimeout and setInterval.

                 Ø useEffect accepts two arguments. The second argument is optional
                
            useEffect(<Callback function>, <dependency>)

        Ø  Whenever useEffect use without any dependency then it will                       execute callback function on every render whenever any  state                           change in component. 

Ø  Whenever useEffect use with empty array then it will execute callback function only once whenever component gets loaded. 

Ø  Whenever useEffect use with dependency then it will execute callback function whenever component gets loaded and after that dependency changes again it will execute callback function.

            Example : 1 useEffect without/With/EmptyArray any                                 dependency

            
import React, { useEffect, usestate } from 'react'

            import './App.css'

 

function App()  {

const [count, setCount] = usestate(0)

const [name, setName] = useState(“Hello”)

 

/*Without dependency - Runs on every render*/

useEffect(() => {

            setTimeout(()=>{

            setCount(count => count+1);

},2000)

}) 

/*Empty array - runs only on first render*/

/*useEffect(() => {

            setTimeout(()=>{

            setCount(count => count+1);

},2000)

},[])*/

 

/*With dependency - runs on first render and anytime when it's dependency                 value changed*/

/*useEffect(() => {

            setTimeout(()=>{

            setCount(count => count+1);

},2000)

},[count,name])*/

 

return (

<> 

<h1>I've rendered {count) times!</h1>

</>

)

}

export default App

O/P

Without Dependency




Empty Array []








With Dependency




Note:- To continue increasing the count, remove React.StrictMode from App.js, it will do an additional run time check in the development environment to make sure that your react app is safe





No comments:

Post a Comment

React Hooks - custom Hook

  v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...