useEffect is a built-in React Hook that allows you to perform side effects in function components. Side effects typically include data fetching, subscriptions, or manually changing the DOM in reaction to component updates.
How it works ?
useEffect in React schedules side effects to run after rendering. It checks dependencies to determine when to re-run. It supports cleanup functions for resource management. This hook streamlines managing side effects in functional components, enhancing code organization and efficiency.
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.
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 syntax accepts two arguments where the second argument is optional
React useEffect Hook Syntax:
useEffect(<FUNCTION>, <DEPENDECY>)
React useEffect Hook ShortHand for:
FUNCTION: contains the code to be executed when useEffect triggers.
DEPENDENCY: is an optional parameter, useEffect triggers when the given dependency is changed.
Controlling side effects in useEffect :
To run useEffect on every render do not pass any dependency
useEffect(()->{
// Example Code
})
To run useEffect only once on the first render pass any empty array in the dependecy
useEffect(()->{
// Example Code
}, [] )
To run useEffect on change of a particular value. Pass the state and props in the dependency array
useEffect(()->{
// Example Code
}, [props, state] )
React UseEffect Hook Example:
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: This example demonstrates the use of useEffect Hooks to render the click counts.
// 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;
useEffect triggers a function on every component render, leveraging React to execute specified tasks efficiently.
Positioned within the component, it grants easy access to state and props without additional coding.
For replicating lifecycle methods in functional components, copy and customize the provided code snippet according to your needs.
Ways to mimic lifecycle methods using useEffect hook
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.
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
useEffect
useEffect is a built-in React Hook that allows you to perform side effects in function components. Side effects typically include data fetching, subscriptions, or manually changing the DOM in reaction to component updates.
How it works ?
useEffect in React schedules side effects to run after rendering. It checks dependencies to determine when to re-run. It supports cleanup functions for resource management. This hook streamlines managing side effects in functional components, enhancing code organization and efficiency.
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.
Importing useEffect hook
To import the useEffect hook, write the following code at the top level of your component
Structure of useEffect hook
The useEffect hook syntax accepts two arguments where the second argument is optional
React useEffect Hook Syntax:
React useEffect Hook ShortHand for:
Controlling side effects in useEffect :
React UseEffect Hook Example: 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: This example demonstrates the use of useEffect Hooks to render the click counts.
Ways to mimic lifecycle methods using useEffect hook 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.
For componentDidMount
For componentDidUpdate
For componentWillUnmount