Understanding and using React useEffect

Understanding and using React useEffect

The new useEffec hook function in React16.8 is used to handle side effects.

To give a simple example of the so-called "side effects", if you have a cold and it would be fine if you take some medicine, but after taking the medicine you find that your body is allergic to it, and this "allergy" is the side effect.

In React, we originally just wanted to render the DOM and display it on the page, but in addition to the DOM, there is also data, and this data must be obtained from an external data source. The process of "obtaining the external data source" is a side effect.

For how to use useEffect, you can refer to the examples given on the official website. Here we mainly summarize the problems encountered in the use of useEffect.

Avoid repetitive rendering loops

Use useEffect to receive an array as the second parameter, and use the second parameter as dependency. Each time the DOM is rendered and the side effect function is executed, a shallow comparison is made to see if the values ​​before and after dependency rendering are consistent. If they are inconsistent, the side effect is executed, otherwise it is not executed. If the dependency is an empty array [], that is, no variable to be compared is passed in, the comparison result will always remain unchanged, and the side effect logic can only be executed once.

useEffect(() => {
  setTimeout(() => {    
        setCounter(counter + 1);  
    }, 300)
}, []);

In addition, if we want to get external data by clicking the refresh button but don’t want to cause an infinite loop, we can use a variable as a "switch" to achieve the goal while avoiding cyclic rendering of the DOM.

It’s too troublesome to draw animated pictures, please read the annotations and use your imagination😂

function App() { const [count, setCount] = useState(0); const [loading, setLoading] = useState(true); // loading as a switch useEffect(() => { if (loading) { // Note that this is only executed when loading is true setTimeout(() => { setCount(count + 1); setLoading(!loading); // Change loading value }); } }, [loading]); // loading is used as a dependency here
  // After the first DOM rendering is completed, loading is true, the side effect function is executed, the count value becomes 1, and loading becomes false. Since // the value of state is changed, it will be updated and the component will render again, but loading is false at this time, and setTimeout will not be executed.
  // Avoid loop // When you click Refresh, loading changes from false to true, and the function executes an update
  // After the DOM is updated, useEffect is executed. Since loading is already true, the side effect function can be executed, and count changes from 1 to 2.
  // loading changes from true to false again, and so on. . .
  return ( <div> <h3>{count}</h3> <button onClick={() => { setLoading(true); }} > Refresh </button> </div> );}

Regarding the elimination of side effects

useEffect can return a function to clean up the side effects.

  useEffect(() => {    
    ChatAPI.subscribeToFriendStatus(props.id, handleStatusChange);  
    function clear(){
        ChatAPI.unsubscribeFromFriendStatus(props.id, handleStatusChange);
    }  
    return clear;
});

This involves the process of useEffect execution and destruction:

  1. Pass in props.id = 1
  2. Component Rendering
  3. DOM rendering is completed, the side effect function is executed, and the clear side effect function clear is returned, named clear1
  4. Pass in props.id=2
  5. Component Rendering
  6. DOM rendering is completed, execute clear1
  7. The side effect function executes and returns another clear function, named clear2
  8. Component destroyed, clear2 executed

From this we can infer the characteristics of the side effect cleanup function:

  • Each side effect execution returns a cleanup function
  • The cleanup function will be executed before the next side effect function is executed (after DOM rendering is completed)
  • Component destruction also executes a cleanup function

It can also be seen from the printed count value that the clearing function will be executed before the next side effect function is executed, that is, the count value in the clearing function is the count value of the last cache:

Thinking further, when clear1 is executed, props.id is accessed, so is the value of this id 1 or 2?

This involves the concept of closures, because useEffect returns a function, which generates a closure when executed. According to the definition of closure, the returned clear function can access variables outside its own scope. When the component is rendered for the first time, id=1 is passed in, and the value of props.id in the clear function is 1.

The above is the detailed content of understanding and using React useEffect. For more information about React useEffect, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • A brief discussion on the pitfalls of react useEffect closure
  • The difference between useEffect and useLayoutEffect in React

<<:  Summary of Creating and Using Array Methods in Bash Scripts

>>:  Detailed explanation of how to mount remote file systems via SSH on Linux

Recommend

About using Alibaba's iconfont vector icon in Vue

There are many import methods on the Internet, an...

MySQL log trigger implementation code

SQL statement DROP TRIGGER IF EXISTS sys_menu_edi...

CSS stacking and z-index example code

Cascading and Cascading Levels HTML elements are ...

Detailed explanation of mysql5.6 master-slave setup and asynchronous issues

Table of contents 1. MySQL master-slave replicati...

How to use vs2019 for Linux remote development

Usually, there are two options when we develop Li...

CSS Sticky Footer Implementation Code

This article introduces the CSS Sticky Footer imp...

MySQL index leftmost principle example code

Preface I was recently reading about MySQL indexe...

Detailed steps for installing MinIO on Docker

Table of contents 1. Check whether the docker env...

Implementation of Linux command line wildcards and escape characters

If we want to perform batch operations on a type ...

RGBA alpha transparency conversion calculation table

Conversion between rgba and filter values ​​under...

Two ways to implement text stroke in CSS3 (summary)

question Recently I encountered a requirement to ...

Installation steps of mysql under linux

1. Download the mysql tar file: https://dev.mysql...

How to solve the problem of FileZilla_Server:425 Can't open data connection

When installing FileZilla Server on the server, t...

How to deploy Go web applications using Docker

Table of contents Why do we need Docker? Docker d...