The React hooks are a very powerful feature that allows us to hook into the React functionality. It is a JavaScript function that can be used or called inside the React functional component. You cannot use a hook inside the custom function in the component. So, it is necessary to call the hook function at the top level. In our last post, we have already seen the useState() hook for setting and retrieving the state value(s). You can create the custom hook in React functional component also. That we will see in the upcoming post. Today, in this post, we will see React useEffect hook. The useEffect hook works to perform side effects in the functional component. That means when any certain changes have occurred in the component the React useEffect hook can be called. It updates the DOM immediately when something change occurred in the component.
In the class component, React has the life cycle methods. Here, the useEffect is equivalent to componentDidMount(), componentDidUpdate(), componentWillUnmount() life cycle methods. Let’s see an example for a better understanding of using the useEffect hook in React js.
Prerequisites
Before moving to this post, I am assuming you are familiar with the below concepts.
- React Basics
- Class and function component in React
- State in class and function component
- useState hook
For creating a React app, you must have the Node js installed in your system. When you are ready, let’s hit the below command to create a React app.
What is useEffect hook in React js
The useEffect hook is a JavaScript function that is used in the functional component in React. It is equivalent to the React life cycle methods such are –
- componentDidMount
- componentDidUpdate
- componentWillUnmount
These life cycle methods are used in the class component. So, you cannot go with these methods in the functional component. Hence, React hook has the useEffect() function to achieve the life cycle methods functionality. It works to perform any action based on certain changes that happened in the component. For example- In the class component the componentDidMount calls when the component invokes and mounts the first time.
Also, the componentDidUpdate calls when some change happens in the component. Lastly, for the clean up when the component will unmount then the componentWillUnmount method invokes.
Similarly, in the case of useEffect hook, there are two types of effects-
- Effects Without Cleanup
- Effects With Cleanup
We will see both types with the example here. So, let’s start by creating a new app in React.
How to Create Loading Spinner Using Bootstrap in React JS
Create React App For Using useEffect Hook
Open the terminal and hit the below command for creating a new app in React.
npx create-react-app blog
It will take a couple of minutes to install the React library in a new folder named blog.
After finishing the installation, let’s navigate to the app folder and run it.
cd blog
npm start
It will start the development server on the 3000 port by default. Also, it will redirect to the default browser automatically.
File Upload in React JS Using Laravel 8 RESTful API
React useState Hook
Initially, we will convert the class component to the function component. So, by default, we have a component named App.js. Therefore, we will be using the same component by removing all the code from it. Now, let’s convert it to the functional component.
import React, { useState } from 'react';
import './App.css';
export const App = () => {
const [message, setMessage] = useState('Hello! this is state hook');
return (
<div className='container'>
<h4> {message} </h4>
</div>
);
};
In the above code, I have created a state and set a message in the initial state. Also, I have imported a stylesheet file named App.css. So, just add the below basic style in it.
.container {
width: 50%;
margin: 100px auto;
text-align: center;
}
Check the result in the browser.
In the above result, we have the message that is coming from the state. Now, let’s apply the effect on it.
How to Use Axios in React JS For API Requests Handling
React useEffect Hook
For a better understanding of useEffect, I have used the useState hook in the above snippet. Now, let’s use the effect. For using the effect hook, you will need to import the hook as we did for the state hook.
The basic syntax of the useEffect hook is –
useEffect(() => {
effect
return () => {
cleanup
};
}, [input]);
- In the syntax, you may see inside the useEffect function there is the effect section. That means when the component has any change then that effect (action) should apply here.
- There is a cleanup that is equivalent to the componentWillUnmount method.
- In the callback there is an array. If you set this array to empty then it will call the effect at the first time when the component will mount. But, if you set some variable or any other action then the effect will be called only when that certain value or action will be there. By default, if you don’t set any parameter in the callback then it will everytime on render. This may reduce the performance of the application.
Let’s understand through an example here. After importing the useEffect from React library, just add the below snippet.
import React, { useState, useEffect } from 'react';
import './App.css';
export const App = () => {
const [message, setMessage] = useState('Hello! this is state hook');
useEffect(() => {
console.log(message);
setMessage('This is effect hook');
});
return (
<div className='container'>
<h4> {message} </h4>
</div>
);
};
In the above code, I have set the message inside the effect hook. This will replace the existing message with a new one. See the result the initial state message is replaced when the component is loaded. But, in the console, you can see the message is called two times.
Also, in the console, you may see the message. The first message is of the initial state. But, when the component is mounted then using its effect it changed the message.
Form Handling in React JS With Validation Using React State
useEffect Hook in React js with Timeout
Let’s see the useEffect with setTimeout() function. Here, we will update the state message with some delay.
import React, { useState, useEffect } from 'react';
import './App.css';
export const App = () => {
const [message, setMessage] = useState('Hello! this is state hook');
useEffect(() => {
console.log(message);
setTimeout(() => {
setMessage('This is effect hook');
}, 2000);
});
return (
<div className='container'>
<h4> {message} </h4>
</div>
);
};
Check the response, here, we have updated the message with a delay of 2 seconds.
If you want to call the effect only one time, not on the basis of each rendering of any other effect. Then you can set the empty array in the callback of the useEffect() function. This will call the effect method only when the component will mount.
import React, { useState, useEffect } from 'react';
import './App.css';
export const App = () => {
const [message, setMessage] = useState('Hello! this is state hook');
useEffect(() => {
console.log(message);
setMessage('This is effect hook');
}, []);
return (
<div className='container'>
<h4> {message} </h4>
</div>
);
};
See the response in the result. The message is changed in the UI and in the console, the message is called once on component mounted.
Brief Overview of React Routing Using React Router DOM
React useEffect with Some Action
Let’s modify the example with a condition and action. We want to call effect when a certain condition will match and also, it required some value to perform the action.
import React, { useState, useEffect } from 'react';
import './App.css';
export const App = () => {
const [message, setMessage] = useState('Hello! this is state hook');
const [counter, setCounter] = useState(0);
useEffect(() => {
console.log(message);
if (counter === 4) {
setMessage('This is effect hook');
}
}, []);
const increment = () => {
setCounter(counter+1);
};
return (
<div className='container'>
<h4> {message} </h4>
<h4> {counter} </h4>
<button onClick={increment}> Increment </button>
</div>
);
};
In the above code, I have added a counter button to increment the counter value by 1. In the useEffect, I have set a condition when the counter value will be 4 the message will be changed. But in the callback, I have not passed any action. It is just an empty array. So, it will be rendered only one time on the component mount.
So, here the message is not changed because the counter is incrementing but in the callback, there is no action. So, the message is not updated.
Now, let’s pass action in the callback. Here, we want when the counter exists and it is equal to 4. Then it will update the message.
import React, { useState, useEffect } from 'react';
import './App.css';
export const App = () => {
const [message, setMessage] = useState('Hello! this is state hook');
const [counter, setCounter] = useState(0);
useEffect(() => {
console.log(message);
if (counter === 4) {
setMessage('This is effect hook');
}
}, [counter]);
const increment = () => {
setCounter(counter+1);
};
return (
<div className='container'>
<h4> {message} </h4>
<h4> {counter} </h4>
<button onClick={increment}> Increment </button>
</div>
);
};
The result is here. You can see the effect has been applied on the basis of the counter value and condition.
Create a Todo App in React Using Laravel 8 RESTful APIs
So, that’s it for the useEffect hook in React js.
Final Words
We used the useState() hook to implement the useEffect() hook in this post. The useEffect is the equivalent to the React life cycle methods. So, you can perform any action based on the component rendering. As per the life cycle methods, there are different methods that are used in the React class component. But, you cannot use directly the life cycle methods in the functional component. So, you will require to go through the React useEffect Hook in the functional component. I hope this post will be helpful in learning to you at a beginner level.
Leave a Reply