Home >Web Front-end >JS Tutorial >A brief analysis of the use of useEffecfa function in React Hook

A brief analysis of the use of useEffecfa function in React Hook

青灯夜游
青灯夜游forward
2022-11-14 20:02:191115browse

This article will introduce you to the useEffecfa function in React Hook and talk about the usage details of useEffecfa function. I hope it will be helpful to you!

A brief analysis of the use of useEffecfa function in React Hook

##Detailed analysis of useEffect

Basic use of useEffec

Continued from the above, in the previous article we explained State Hook. We can already define state in functional components through this hook. [Related recommendations:

Redis video tutorial, Programming video]

We know that there can be life cycle functions in class components, then How to define functions similar to the life cycle in the function component?

Effect Hook allows you to complete some functions similar to the life cycle in the class;

Facts Similar to network requests, manual DOM update, and some event monitoring, they are all side effects of React updating DOM;

So the Hook that completes these functions is called Effect Hook;

Suppose we have a requirement now: the title in the page always displays the number of counter, use class component and Hook to implement the :

class respectively Component implementation

import React, { PureComponent } from 'react'

export class App extends PureComponent {
  constructor() {
    super()

    this.state = {
      counter: 100
    }
  }

  // 进入页面时, 标题显示counter
  componentDidMount() {
    document.title = this.state.counter
  }

  // 数据发生变化时, 让标题一起变化
  componentDidUpdate() {
    document.title = this.state.counter
  }

  render() {
    const { counter } = this.state

    return (
      <div>
        <h2>{counter}</h2>
        <button onClick={() => this.setState({counter: counter+1})}>+1</button>
      </div>
    )
  }
}

export default App
Function component plus Hook implementation:

    Through the useEffect Hook, you can tell React that it needs to perform certain operations after rendering;
  • useEffect requires us to pass in a callback function. After React completes the update DOM operation (
  • that is, after the component is rendered), this function will be called back;
  • By default, this callback function will be executed whether after the first rendering or after each update; generally we write side-effect operations in this callback function (such as network Request, operate DOM, event monitoring)

So it should be noted that there are many sayings that useEffect is used to simulate the life cycle, but in fact it is not; useEffect can do it Simulates the life cycle, but its main function is to perform side effects

import React, { memo, useEffect, useState } from &#39;react&#39;

const App = memo(() => {
  const [counter, setCounter] = useState(200)

  // useEffect传入一个回调函数, 在页面渲染完成后自动执行
  useEffect(() => {
    // 一般在该回调函数在编写副作用的代码(网络请求, 操作DOM, 事件监听)
    document.title = counter
  })

  return (
    <div>
      <h2>{counter}</h2>
      <button onClick={() => setCounter(counter+1)}>+1</button>
    </div>
  )
})

export default App

Clear side effects (Effect)

During the writing process of class components, we need to clear certain side effect codes in componentWillUnmount:

For example, our previous event bus or Redux Manually calling subscribe;

requires corresponding unsubscription in componentWillUnmount;

How does Effect Hook simulate componentWillUnmount?

useEffect pass The entered callback function A itself can have a return value, which is another callback function B:

type EffectCallback = () = > (void | (() => void | undefined));

Why should we return a function in effect?

This is an optional cleanup mechanism for effects. Each effect can return a clearing function;

This way the logic of

adding and removingsubscriptions can be put together;

They are all part of the effect;

When does React clear the effect?

React will perform the clearing operation when the component is updated and uninstalled, canceling the last monitoring. Only the current listener is left;

As learned before, the effect will be executed every time it is rendered;

import React, { memo, useEffect } from &#39;react&#39;

const App = memo(() => {
  useEffect(() => {
    // 监听store数据发生改变
    const unsubscribe = store.subscribe(() => {

    })

    // 返回值是一个回调函数, 该回调函数在组件重新渲染或者要卸载时执行
    return () => {
      // 取消监听操作
      unsubscribe()
    }
  })

  return (
    <div>
      <h2>App</h2>
    </div>
  )
})

export default App

Use multiple useEffect

One of the purposes of using Hook is to solve the problem of often putting a lot of logic together in the life cycle of a class:

For example, network requests, event monitoring, and manual modification of DOM are often placed in componentDidMount;

Multiple Effect Hooks can be used in a function component, and we can separate the logic into Different useEffect:

import React, { memo, useEffect } from &#39;react&#39;

const App = memo(() => {
  // 监听的useEffect
  useEffect(() => {
    console.log("监听的代码逻辑")

    return () => {
      console.log("取消的监听代码逻辑")
    }
  })

  // 发送网络请求的useEffect
  useEffect(() => {
    console.log("网络请求的代码逻辑")
  })

  // 操作DOM的useEffect
  useEffect(() => {
    console.log("操作DOM的代码逻辑")
  })

  return (
    <div>
      App
    </div>
  )
})

export default App

Hook allows us to separate them according to the purpose of the code, instead of putting a lot of logic together like the life cycle function:

React will call each effect in the

component in sequence in the order in which the effect is declared;


useEffect performance Optimization

By default, useEffect’s callback function will be re-executed every time it is rendered, but this will cause two problems:

We only want to execute some codes once (

For example, network requests can be executed once during the first rendering of the component, and there is no need to execute multiple times), similar to componentDidMount and componentWillUnmount in class components Things accomplished;

In addition, multiple executions will also cause certain performance problems;

How do we decide when useEffect should be executed and when it should not be executed? What?

useEffect actually has two parameters:

  • 参数一: 执行的回调函数, 这个参数我们已经使用过了不再多说;
  • 参数二: 是一个数组类型, 表示 该useEffect在哪些state发生变化时,才重新执行;(受谁的影响才会重新执行)

案例练习:

受count影响的Effect;

import React, { memo, useEffect, useState } from &#39;react&#39;

const App = memo(() => {
  const [counter, setCounter] = useState(100)
  
  // 发送网络请求的useEffect, 只有在counter发生改变时才会重新执行
  useEffect(() => {
    console.log("网络请求的代码逻辑")
  }, [counter])

  return (
    <div>
      <h2 onClick={() => setCounter(counter+1)}>{counter}</h2>
    </div>
  )
})

export default App

但是,如果一个函数我们不希望依赖任何的内容时,也可以传入一个空的数组 []:

那么这里的两个回调函数分别对应的就是componentDidMount和componentWillUnmount生命周期函数了;

import React, { memo, useEffect, useState } from &#39;react&#39;

const App = memo(() => {
  const [counter, setCounter] = useState(100)
  
  // 传入空数组表示不受任何数据依赖
  useEffect(() => {
    // 此时传入的参数一这个回调函数: 相当于componentDidMount
    console.log("监听的代码逻辑")

    // 参数一这个回调函数的返回值: 相当于componentWillUnmount
    return () => {
      console.log("取消的监听代码逻辑")
    }
  }, [])

  return (
    <div>
      <h2 onClick={() => setCounter(counter+1)}>{counter}</h2>
    </div>
  )
})

export default App

总结: useEffect可以模拟之前的class组件的生命周期(类似而不是相等), 并且它比原来的生命周期更加强大, 青出于蓝而胜于蓝

更多编程相关知识,请访问:编程教学!!

The above is the detailed content of A brief analysis of the use of useEffecfa function in React Hook. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete