DEV Community

Cover image for useEffect() Hook in React
Mrityunjay-Palled
Mrityunjay-Palled

Posted on

useEffect() Hook in React

The useEffect hook is used to introduce side effects into our functional component. Making an API call to fetch the data from the server, manually changing the DOM, and setting up the subscriptions are all examples of side effects.If you are familiar with class-based component life cycle methods, then the useEffect hook acts as the combined form of the componentDidMount, componentDidUpdate, and componentWillUnmount methods.Now let's see how we can import the useEffect hook into our react application.

import { useEffect } from 'react'
Enter fullscreen mode Exit fullscreen mode

The useEffect hook takes two parameters. One is a callback function that contains actual side effects, and another is an optional dependency array.By default useEffect runs both after a first render and after every update. React always guarantees that DOM has been updated by the time it runs the effects

useEffect with no dependency:

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

const App = () => {
  const [count,setCount]=useState(0)
  useEffect(()=>{
    //runs on every render
    console.log(`You clicked ${count} times`)
  })
  return (
     <button onClick={()=>setCount(count+1)}>
      click here
     </button>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

Since no dependency array is passed in the above example, the useEffect is executed after each render.

useEffect with empty array as a dependency:

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

const App = () => {
  const [count,setCount]=useState(0)
  useEffect(()=>{
    //runs only after the initial render
    console.log(`You clicked ${count} times`)
  },[])

  return (
    <button onClick={()=>setCount(count+1)}>
      click here
    </button>
  )
}
export default App

Enter fullscreen mode Exit fullscreen mode

Since we have added an empty array as the dependency. This causes the useEffect to run only once after initial rendering.No matter how many times we click the button this will only show initial value of count

useEffect with state or props variable as a dependency:

import React, { useState } from "react";
import { useEffect } from "react";

const App = () => {
  const [incrementCount, setIncrementCount] = useState(0);
  const [decrementCount,setDecrementCount] = useState(0);

  useEffect(() => {
    //runs only when the value of incrementCount changes
    console.log(`Count after increment: ${incrementCount}`);
  }, [incrementCount]);

  return (
    <>
      <button onClick={() => setIncrementCount(incrementCount + 1)}>
        click here to increment a count
      </button>
      <button onClick={() => setDecrementCount(decrementCount - 1)}>
        click here to decrement a count
      </button>
    </>
  );
};
export default App;

Enter fullscreen mode Exit fullscreen mode

As we see above, we are passing the state variable incrementCount as the dependency to the useEffect, hence the useEffect will run only when the value of incrementCount changes.

useEffect with cleanup:

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

const App = () => {
  const [count,setCount]=useState(0)
  useEffect(()=>{
    let intervalId=setInterval(()=>{
      console.log(`You clicked ${count} times`)
    },1000)
    return ()=>{
      clearInterval(intervalId)
    }
  },[count])

  return (
    <button onClick={()=>setCount(count+1)}>
      click here
    </button>
  )
}
export default App

Enter fullscreen mode Exit fullscreen mode

As we see above, there is a return function, which is also called the cleanup function. This function cleans up the timer every time the value of count changes and starts it from the beginning.

Top comments (0)