Using React UseEffect Hook to Improve Performance

Using React UseEffect Hook to Improve Performance

React 16.8 has a new feature called React Hooks. They enable you to transform function components to stateful components. Without building a class component, you may leverage state, React lifecycle methods, and other features.

One of the new additions is UseEffect; you may need to execute further operations after you've rendered a component; by using this hook, React will remember the function you gave after the DOM updates. It allows us to execute and Data fetching, subscription setup, and manually modifying the DOM in React are examples of side effects. UseEffect is a combination of Lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount.

Cleaning up or applying the effect after each render may cause performance issues in some circumstances.

In a class component, the problem will be fixed by implementing another comparison with prevProps or prevState in our componentDidUpdate method.

componentDidUpdate(prevProps, prevState) {
  if (prevState.post !== this.state.post) {
    document.title = `You viewed ${this.state.post} times`;
  }
}

However, using UseEffect, you may instruct React to avoid an effect if a certain value hasn't changed between re-renders. An array is supplied as an optional second parameter to useEffect to do this.

If you use this optimization, make sure the array contains all dependent values from the component scope that vary over time and are utilized by the effect.

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

function PostDetails (props) {
const [post, setPost] = useState({});
const { id } = useParams();

useEffect(() => {
    const getPost = async () => {
      const response = await connectToApi(`/posts/${id}`);
      setPost(response.data);
    };
    getPosts();
  }, [post]); // effect will only appply as long as post keep changing
}

You can pass an empty array ([]) as a second argument to avoid re-running effects and clean it up only once (on mount and unmount). This informs React that you don't require any data from the props or state and that it should never be re-run.

Reference:

More information about Hooks can be found in the React Docs.