What Is the useEffect Hook In React?

The useEffect Hook is React Hook which is used to create side effects in function components. The useeffect hook directly updates the DOM and is used to fetch data. The useEffect hook takes two arguments one is function and the other is dependency.

useEffect(<function>,<dependency>);

Basic Structure:

Declare:

First of all, call the useEffect at the top of the component and then declare it

Dependencies:

The useEffect creates a control effect that can not be re-run every time, it only re-runs when needed.

Cleanup:

The useEffect hook uses the cleanup function when we want to stop, undo, and clean up a specific task.

Here is the basic structure of the useEffect hook

useEffect(() => {
    effect
    return () => {
      cleanup
    };
  }, [input]);

useEffect in React js:

Here is an example of useEffect in which we want to increment with 1 and it changes automatically, and every second it increment with 1. Here is also the increment with the help of  usestate  hook

Here is an example:

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

export default function App() {
  const [count , setCount] = useState(0)
  useEffect(() => {
    setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);
  })
  return (
    <>
    <h1>{count}</h1>
    </>
  )
}

Control UseEffect:

In control useEffect, we use a button, and then clicking it increments only one 

Here is an example:

import React,{useEffect,useState} from 'react'
function App() {
  const [count , setCount] = useState(0)
  useEffect(() => {
   document.title=("incre")
  });
  return (
    <>
    <h1>{count}</h1>
    <button type="button" onClick={()=>setCount(count+1)}>INCRE</button>
    </>
  )
}
export default App;

OUTPUT:

useEffect Hook

Condition In useEffect Hook:

We also use the condition inside the useEffect hook as below if the count is equal to or greater than 1 then the title is Increment otherwise the title is useeffect.

import React,{useEffect,useState} from 'react'
function App() {
  const [count , setCount] = useState(0)
  useEffect(() => {
     if (count=>5) {
      document.title=("increment")
     } else {
      document.title=("udecre")
     }
  },[count]);
  return (
    <>
    <h1>{count}</h1>
    <button type="button" onClick={()=>setCount(count+1)}>INCRE</button>
    </>
  )
}
export default App

You can also check out the condition in usestate hook

useEffect Hook async:

useEffect uses the async await to fetch data from the API and then display it. We also use the useState hook to show the value of the API and we use the async await in the useEffect or outside the useEffect hook in the following way

import React,{useState,useEffect} from 'react'
export default function Api() {
  const[ipdata,setIPdata]=useState("")
  const actualDeta=async()=>{
    try {
        const res=await fetch("https://api.breakingbadquotes.xyz/v1/quotes");
        const actualData=await res.json();
        setIPdata(actualData[0])
        
    } catch (error) {
      console.log(error)
    }
  }
   
  useEffect(() => {
   
    actualDeta()
  });
  console.log(ipdata)

OUTPUT:

useEffect Hook

useEffect Hook Dependency Array

It fetches data nonstop showing results automatically so we use the array dependency to show the data one by one after refreshing the tab. We use array dependency for this purpose. We use any value in the array dependency.

Here is an example:

import React,{useState,useEffect} from 'react'
export default function Api() {
  const[ipdata,setIPdata]=useState("")
  const actualDeta=async()=>{
    try {
        const res=await fetch("https://api.breakingbadquotes.xyz/v1/quotes");
        const actualData=await res.json();
        setIPdata(actualData[0])
        
    } catch (error) {
      console.log(error)
    }
  }
   
  useEffect(() => {
   
    actualDeta()
  },[]);
  console.log(ipdata)

useEffect Hook Empty Array:

useEffect empty array is used to fetch the data only in only time. It renders the data one time only and this function is called only the first time. This helps us to improve our website performance because it avoids unnecessary requests. You can see the full detail of array and its method

useEffect Hook Cleanup Function:

When useEffect fetches and render data it uses the memory and stores it in the memory, so the performance of the application is reduced due to unnecessary render and request. It causes a problem of memory leaks so we used the cleanup function in useEffect after a return.

Here is an example:

import { useState, useEffect } from "react";
export default function App() {
  const [count, setCount] = useState(1);
  useEffect(() => {
    let cleanup = setTimeout(() => {
    setCount((count) => count + 2);
  }, 1000);
  return () => clearTimeout(cleanup)
  }, []);
  return <h1>I've rendered {count} times!</h1>;
}

About Author

Leave a comment