What is useEffect hook in React?

 useEffect hook

The useEffect in ReactJS is used to handle the side effects 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

Why choose useEffect hook?

useEffect hook is used to handle side effects in functional components, such as fetching data, updating the DOM, and setting up subscriptions or timers. It is used to mimic the lifecycle methods of class-based components. 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. 

How does it work?

  • You call useEffect with a callback function that contains the side effect logic.
  • By default, this function runs after every render of the component.
  • You can optionally provide a dependency array as the second argument.
  • The effect will only run again if any of the values in the dependency array change.
Example:

// File name - HookCounterOne.js
// useEffect is defined here
 
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;

Leave a comment

Your email address will not be published. Required fields are marked *