useEffect in react

It is a side effect executed in the function component. The side effect refers to the function that will be executed every time the component is updated, and can be used to replace the life cycle.

1. Basic Usage

import {
    
     useEffect } from "react";
useEffect(()=>{
    
    
    console.log('副作用');   
});

2. Side effects are divided into those that need to be cleared and those that do not need to be cleared
. If a timer is set, the timer needs to be turned off when the component is unloaded, and this is what needs to be cleared.

What needs to be cleared needs to return a function in the side effect, and the returned function writes the required code logic.

import {
    
     useEffect } from "react";
useEffect(()=>{
    
    
    return () => {
    
    
        console.log('组件卸载');
    }
});

If you don't need to clear, you don't need to write return

3. Pass in the second parameter.
If not passed in, it will be executed when the component is updated.

Pass in an empty array[]

It means that it runs only once (executed only when the component is mounted and unloaded). When the side effect does not return a function, it can be used as a life cycle, and when the componentDidMountfunction is returned, it can be componentWillUnmountused as a life cycle.

// 当做 componentDidMount使用
import {
    
     useEffect } from "react";
useEffect(()=>{
    
    
    console.log('页面渲染完成');
}, []);
// 当做 componentWillUnmount使用
import {
    
     useEffect } from "react";
useEffect(()=>{
    
    
    return () => {
    
    
        console.log('组件卸载');
    }
}, []);

Pass in the array [item]

import {
    
     useEffect} from "react";
import {
    
     useSelector} from "react-redux";

const {
    
     num } = useSelector((state) => ({
    
    
  num: state.num,
}));
useEffect(()=>{
    
    
    console.log('执行了');
}, [num]);

When the array is not empty, numthe value will be detected when the component is updated. If the updated value is different from the old value, the effect will be called, and if they are the same, the execution will be skipped.

If the array passes in multiple parameters, the effect will be executed as long as one item is changed.

Guess you like

Origin blog.csdn.net/weixin_45289656/article/details/129139932