ReactJS useEffect Hook
React useEffect hook handles the effects of the dependency array. The useEffect
Hook allows us to perform side effects on the components. fetching data, directly updating the DOM and timers are some side effects. It is called every time any state if the dependency array is modified or updated.
In this article, we’ll explore what the useEffect hook does, how to use it, common use cases, and some best practices to follow.
Table of Content
What is useEffect hook in React?
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. The useEffect hook is vital for managing side effects in functional components.
Syntax:
useEffect(() => {
// Side effect logic goes here
return () => {
// Cleanup logic (optional)
};
}, [dependencies]);
- Effect function: This is where your side effect code runs.
- Cleanup function: This optional return function cleans up side effects like subscriptions or timers when the component unmounts.
- Dependencies array: React re-runs the effect if any of the values in this array change.
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.
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 :
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] )
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.
//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;
//App.js
// Importing and using HookCounterOne
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.
useEffect
triggers a function on every component render, using 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.
For componentDidMount
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)
For componentDidUpdate
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
For componentWillUnmount
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