Wednesday, December 25, 2024
Google search engine
HomeLanguagesReactJS useEffect Hook

ReactJS useEffect Hook

In this article, we will learn about the useEffect hook in React, its uses, and implementation with the help of an example.

What is useEffect hook?

The useEffect hook in React is use to handle the side effects in React such as fetching data, and updating DOM. This hook runs on every render but there is also a way of using a dependency array using which we can control the effect of rendering

Reason to choose useEffect hook:

The motivation behind the introduction of useEffect Hook is to eliminate the side effects of using class-based components. For example, tasks like updating the DOM, fetching data from API end-points, setting up subscriptions or timers, etc can lead to unwarranted side effects. Since the render method is too quick to produce a side-effect, one needs to use life cycle methods to observe the side effects. 

Importing useEffect hook

To import the useEffect hook, write the following code at the top level of your component

import { useEffect } from "react"

Structure of useEffect hook

The useEffect hook accepts two arguments where the second argument is optional

Syntax:

useEffect(<FUNCTION>, <DEPENDECY>)

We know that the useEffect() is used for causing side effects in functional components and it is also capable of handling componentDidMount(), componentDidUpdate(), and componentWillUnmount() life-cycle methods of class-based components into the functional components.

Ways of controlling side effects in useEffect hook

1. To run useEffect on every render do not pass any dependency

useEffect(()->{
// Example Code
})

2. To run useEffect only once on the first render pass any empty array in the dependecy

useEffect(()->{
// Example Code
}, [] )

3. To run useEffect on change of a particular value. Pass the state and props in the dependency array

useEffect(()->{
// Example Code
}, [props, state] )

Let’s look at an example of how to use the useEffect hook as a feature that can mimic the life-cycle methods but in functional components. The functional component will look like the code below:

Example: Write the following code in the respective file

  • src/components/HookCounterOne.js: useEffect is implemented in this component 
  • App.js: The component is imported and rendered using this component

Javascript




//HookCounterOne.js File
import { useState, useEffect } from "react";
  
function HookCounterOne() {
    const [count, setCount] = useState(0);
  
    useEffect(() => {
        document.title = `You clicked ${count} times`;
    }, [count]);
  
    return (
        <div>
            <button onClick={() => setCount((prevCount) => prevCount + 1)}>
                Click {count} times{" "}
            </button>
        </div>
    );
}
export default HookCounterOne;


Javascript




//App.js File
import React from "react";
import "./App.css";
import HookCounterOne from "./components/HookCounterOne";
  
function App() {
    return (
        <div className="App">
            <HookCounterOne />
        </div>
    );
}
export default App;


Output: Initially, the document title reads “You clicked 0 times”. when you click on the button, the count value increments, and the document title is updated.

gfg

When we specify useEffect we are basically requesting react to execute the function that we pass in the useEffect function as an argument, every time the component renders. The second thing to make note of is that useEffect is used inside the component as by doing this we can easily access the components state and props without having to write any additional code.
 If you want to use the react lifecycle methods in functional components then copy and paste the code snippet given below and customize them as per your requirement.

Ways to mimic lifecycle methods using useEffect hook

useEffect(()=>{
//You can add your code here for mounting phase of component
console.log("Mounting in Functional Component")
},[])
// adding an empty array ensures that the useEffect is only triggered once
// (when the component mounts)
useEffect(()=>{
//You can add your code for updating phase of component
console.log("Updating in Functional Component")
},[values])
//values triggers re render whenever they are updated in your program,
//you can add multiple values by separating them by commas
useEffect(()=>{
return()=>{
//You can add your code for unmounting phase of component
console.log("Functional Component Removed ")
}
},[])
//Write all the code of unmounting phase only inside the callback function

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments