What is the useEffect Hook in React?

Hooks are a new feature introduced in version 16.8 of React.JS. Hooks are special functions that enable the use of state and several other features in functional components available in class-based components. One of these special functions is useEffect.

The useEffect hook can be used to perform operations (or side effects) on the following occasions in functional components:

  • when a component is rendered (componentDidMount function in class-based components)
  • when a component changes (componentDidUpdate function in class-based components)
  • before a component is unmounted/removed (componentWillUnmount function in class-based components)

The operations performed through the useEffect hook can include requesting data from the server, changing the DOM, etc. We can also use multiple useEffect hooks to divide the logic of the code.

Syntax

useEffect(callback,[dependencies]);

In the above snippet of code, callback refers to the function executed when the useEffect hook is triggered. This could also be an arrow function. The parameter dependencies refers to an optional list of variables. The useEffect hook is only triggered if the variables in dependencies change.

Changing the behavior of the useEffect hook

The dependencies parameter also controls when the useEffect hook is triggered. The following are the cases which explain how the dependencies argument controls the useEffect hook:

  • If we wish to trigger the useEffect hook every time the screen is rendered, we will not pass anything in place of the dependencies parameter. The following snippet of code shows this behavior of the useEffect hook:
useEffect(() => {
    //the code here runs everytime the screen is rendered
});
  • If we intend to trigger the useEffect hook only on the initial render, we can do so by passing an empty array in place of the dependencies parameter. This functionality is achieved by using the componentDidMount method in class-based components. For example:
useEffect(() => {
    //the code here runs only on the initial render
}, []);
  • To trigger the useEffect hook only when a variable changes, we can do so by passing the name of that variable in the dependencies list. This functionality is achieved by using the componentDidUpdate method in class-based components. The following snippet of code depicts this behavior of the useEffect hook:
useEffect(() => {
    //the code here runs only when the variable x changes
}, [x]);
  • To trigger the useEffect hook before unmounting the component from the screen, we can return a function from the callback function. The function returned by the callback will be executed before that component is unmounted. After the initial render, this function will be executed for each subsequent execution of the useEffect hook because of the previous execution. This functionality is achieved by using the componentWillUnmount method in class-based components. The following snippet of code depicts this behavior of the useEffect hook:
useEffect(() => {
    //code

    return () => {
    //The code here will run everytime the component is going to be destroyed.
}
});

Example

Consider the following example of a chatbox component:

import React, { useState, useEffect } from 'react';
function ChatboxComponent(props) {
const [userActive, setUserActive] = useState(false);
const [messages, setMessages] = useState([])
useEffect(() => {
const retrieveOldMessages = async () => {
const oldMessages = await axios('https://sampleurl.com/api/old_messages',);
setMessages(oldMessages.data);
};
retrieveOldMessages();
setUserActive(true);
}, []);
return(
<div>
// UI code will be implemented here in JSX
</div>
)
}

In the above snippet of code, we have a chatbox component. We used the useState hook to maintain the state of the component.

Just like the useEffect hook, useState is another popular hook in React, used to create and maintain the state of functional components. More information about the useState hook can be found here.

Whenever the chatbox component is opened, it must retrieve old messages from the database and set the user of the status to ‘active’. To achieve this functionality, we used the useEffect hook.

We defined a function named retrieveOldMessages inside the callback function passed to the useEffect hook. We did this because we cannot make the callback of the useEffect hook asynchronous. To retrieve the data from the database, we need an asynchronous function. Hence, we define an asynchronous function inside the callback and call it.

Once the old messages are retrieved from the backend using the library named axios, we set the state of the messages array and the user’s current status.

Axios is a library that is used with React.JS to communicate with the backend. More information about Axios can be found here and here.

We also passed an empty dependencies array because we want the data to be retrieved only when the component is mounted for the first time. Later on, the state of the component will be maintained.

Copyright ©2024 Educative, Inc. All rights reserved