How to Use useEffect Hooks in React.js Application

Managing Side Effects - A Comprehensive Guide on Effectively Using useEffect Hooks in React.js Applications

February 02, 2022 Dykraf

It is a way to handle lifecycle events in function components, similar to how you would use lifecycle methods in class-based components.

Web Story VersionWeb Story

React hooks are functions that allow you to use state and other React features in functional components, instead of having to use class components. They were introduced in React 16.8 to make it easier to write and manage state in functional components. Some of the most commonly used hooks include useState, useEffect, and useContext. useState allows you to add state to a functional component, useEffect allows you to run side effects such as fetching data or updating the DOM in response to changes in props or state, and useContext allows you to access context in a functional component.

React hooks offer several benefits when compared to traditional class-based components:

1. Code reusability: Hooks allow you to extract stateful logic from a component and share it between multiple components. This makes it easier to write and test reusable logic.

2. Simplified code structure: Hooks allow you to use functional components instead of class components, which can make your code easier to read and understand. Additionally, hooks make it easier to manage state and side effects in your components.

3. Improved performance: With hooks, you can split a component into smaller, independent parts that only re-render when the state or props they depend on change. This can help to improve the performance of your application.

4. Better developer experience: Hooks make it easier to follow best practices, such as separating concerns and managing side effects, which can make it easier to reason about your code and catch bugs early.

5. Community: Since hooks were introduced by React team, it's widely used in the community and many third party libraries are built on top of hooks.

Below is the useEffect explanation sample from React hooks:

useEffect is a hook in React that allows you to perform side effects in function components. It is a way to handle lifecycle events in function components, similar to how you would use lifecycle methods in class-based components.

useEffect is a hook in React that allows you to perform side effects in function components. It is similar to the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class components.

useEffect takes a function as an argument, which will be called after the component renders. This function is referred to as the "effect." You can think of it as a way to tell React to perform some action after the component has finished rendering.

For using useEffect in React js, Here is an example of how you might use useEffect to fetch data from an API and update the component's state with the response:

import { useEffect, useState } from 'react'

function MyComponent() {
  const [data, setData] = useState(null)

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('')
      const data = await response.json()

  }, [])

  return data ? <div>{}</div> : <div>Loading...</div>

The useEffect hook is called with a function that fetches the data from the API. The hook will run this function after the component has finished rendering. The hook will also re-run the function if the component's dependencies (specified in the second argument) change. In this case, we've passed an empty array as the second argument, which means that the hook will only run the function once, after the initial render.

In above example, the effect function is called after the component renders for the first time. It fetches data from an API and sets it in the component's state using the setData function returned by the useState hook.

You can also pass an array of dependencies as a second argument to useEffect. This is used to tell React when to re-run the effect. If the array is empty, the effect will only run once, when the component mounts. If the array contains values, the effect will run every time one of those values changes.

useEffect is a powerful tool that allows you to perform a variety of tasks in your function components, such as fetching data, setting up subscriptions, and changing the DOM. It is an important part of the React ecosystem and is a great way to handle side effects in your web applications.

For example, here is how you could use useEffect to subscribe to a data stream and unsubscribe when the component unmounts:

import { useEffect } from 'react'

function Example({ dataStream }) {
  useEffect(() => {
    const subscription = dataStream.subscribe((data) => {
    return () => {
  }, [dataStream])

  return <div>Streaming data...</div>

In this example, the effect function subscribes to the data stream when the component mounts, and unsubscribes when the component unmounts. The dependency array [dataStream] tells React to re-run the effect whenever the dataStream prop changes.

You can use useEffect() combined with other JavaScript native functions for tasks such as manipulating data and displaying data that involves parent and child relationships. For further details, you can refer to this link. Here is the demo for you to explore:

There are other use cases where you can employ useEffect to fetch data in React. You can read more about using React useEffect with JavaScript promises to fetch data from various endpoint sources in this link.

There are additional use cases where you can leverage React's useEffect and useCallback hooks with JavaScript Promises, such as fetching data and updating the React state with the retrieved information. You can find more details about it here.


I hope this helps! Let me know if you have any questions.


Recent Blog List Content: