ScanSkill

useEffect

useEffect is a React hook used for managing the side effects of the component. By using this Hook, you tell React that your component needs to do something after render. It removes the need for  componentDidMount, componentDidUpdateand and componentWillUnmount.

Syntax

useEffect(callback, [dependencies]);

useEffect() hook accepts 2 arguments: callback and dependencies. The side effects are written inside the callback function. The dependencies argument lets you control when the side-effect runs. There can be three conditions for providing the dependencies:

1. Not provided

The side-effect runs after every rendering.

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

function Example() {
  const [count , setCount ] = useState(0);

  useEffect(()=>{
       console.log('click')
  })                // no dependencies provided

  return (
    <div>
      <button onClick={()=>setCount(count+1)}>click me !</button>
      <span>you clicked {count} times</span>
    </div>
  )
}

export default Example

Output:

https://i0.wp.com/scanskill.com/wp-content/uploads/2022/02/no-dep.png?resize=513%2C112&ssl=1

Here, we can see that the function inside useEffect() ,console.log("click") runs every time we click on the button.

2. An empty array[]

The side-effect runs once after the initial rendering.

useEffect(()=>{
       console.log('click')
  } ,[])                // empty dependencies provided

Output:

https://i0.wp.com/scanskill.com/wp-content/uploads/2022/02/empty.png?resize=586%2C97&ssl=1

Here, we can see that the function inside useEffect() runs only once no matter how many times we click on the button.

3. Has props or state values [prop1, prop2, state1, state2]

The side-effect runs once after initial rendering and after every rendering ONLY IF prop or state changes.

  useEffect(()=>{
       console.log('click')
  }, [count])                // state value provided

Output:

https://i0.wp.com/scanskill.com/wp-content/uploads/2022/02/smm.png?resize=591%2C147&ssl=1

Here, we can see that the function inside useEffect() runs once after initial rendering and after every time we press on the button.