All articles

Exploring the Power of useEffect

Oct 11, 2023

Exploring the Power of useEffect

React’s useEffect hook is a powerful feature that allows developers to manage side effects in functional components. Whether you’re new to React or an experienced developer, understanding how to effectively use useEffect is crucial for building robust and maintainable applications. In this article, we will dive deep into the world of useEffect and explore its various use cases, best practices, and common pitfalls.

If you are new to React, it is essential to read this article first. However, one downside is that article is written in Chinese.

It’s related to the lifecycle methods of class components. In class components, you have lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount, which allow you to perform certain actions at specific points in the component’s lifecycle. The useEffect hook combines the functionality of these lifecycle methods into this single hook for functional components. The effect specified in the useEffect hook will be executed after every render, which is similar to componentDidMount and componentDidUpdate.

Although, as mentioned before, it can be used for various lifecycle methods, I highly recommend utilizing it solely as componentDidMount. We will elaborate on the reasons for this shortly. The main purpose of useEffect is to hanle side effects that occur when writing components in business logic, such as data fetching, event subscriptions, DOM manipulation, and so on. These side effects can make the component less pure, so it’s important not to deviate from the original intention of useEffect. I perceive useEffect as a double-edged sword, for while it offers ample methods to cater to diverse scenarios, a heedless approach may lead to a project that is excessively malleable, ensnaring us in its intricacies.

Data Structure

To better understand the structure of useEffect, let’s dive into its underlying data structure. In functional components, the memorizedState on its fiber is responsible for storing a linked list of hooks. Each hook can be seen as a node in this linked list, and together they form a Circular Linked List with other effect hooks.

A single effect object comprises the following properties, defined in the code as follows:

const effect: Effect = {
  create,
  destroy,
  deps,
  next,
  tag,
};
  • create: This refers to the first parameter of the useEffect function, which is the callback function.
  • destroy: The return function in the callback function is executed when the effect is destroyed.
  • deps: This represents the dependencies of the effect.
  • next: The next property serves as a pointer to the next hook in the linked list.
  • tag: The type of effect, which can be either useEffect or useLayoutEffect.

antcao.me © 2022-PRESENT

: 0x9aB9C...7ee7d