A brief analysis of the use of useEffecfa function in React Hook
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!
##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:
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 implementationimport 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 AppCopy after login
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 'react' 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 AppCopy after login
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 ofadding and removing
They are all part of the effect;subscriptions can be put together;
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 'react' const App = memo(() => { useEffect(() => { // 监听store数据发生改变 const unsubscribe = store.subscribe(() => { }) // 返回值是一个回调函数, 该回调函数在组件重新渲染或者要卸载时执行 return () => { // 取消监听操作 unsubscribe() } }) return ( <div> <h2>App</h2> </div> ) }) export default AppCopy after login
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 'react' 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 thecomponent 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 'react' 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 'react' 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React code debugging guide: How to quickly locate and resolve front-end bugs Introduction: When developing React applications, you often encounter a variety of bugs that may crash the application or cause incorrect behavior. Therefore, mastering debugging skills is an essential ability for every React developer. This article will introduce some practical techniques for locating and solving front-end bugs, and provide specific code examples to help readers quickly locate and solve bugs in React applications. 1. Selection of debugging tools: In Re

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install
