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

Some suggestions for ensuring MySQL data security

Data is the core asset of an enterprise and one o...

How to automatically import Vue components on demand

Table of contents Global Registration Partial Reg...

An enhanced screenshot and sharing tool for Linux: ScreenCloud

ScreenCloud is a great little app you didn’t even...

A brief discussion on the magical uses of CSS pseudo-elements and pseudo-classes

CSS plays a very important role in a web page. Wi...

Lombok implementation JSR-269

Preface Introduction Lombok is a handy tool, just...

Teach you how to make cool barcode effects

statement : This article teaches you how to imple...

Solution to the low writing efficiency of AIX mounted NFS

Services provided by NFS Mount: Enable the /usr/s...

Teach you how to use webpack to package and compile TypeScript code

TypeScript Bundling webpack integration Usually, ...

Detailed analysis of javascript data proxy and events

Table of contents Data Brokers and Events Review ...

Vue project code splitting solution

Table of contents background Purpose Before split...

Detailed explanation of how to use Vue self-nested tree components

This article shares with you how to use the Vue s...

Zabbix monitors Linux hosts based on snmp

Preface: The Linux host is relatively easy to han...