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 loopsUse 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.
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 effectsuseEffect 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:
From this we can infer the characteristics of the side effect 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:
|
<<: Summary of Creating and Using Array Methods in Bash Scripts
>>: Detailed explanation of how to mount remote file systems via SSH on Linux
There are many import methods on the Internet, an...
SQL statement DROP TRIGGER IF EXISTS sys_menu_edi...
Cascading and Cascading Levels HTML elements are ...
Table of contents 1. MySQL master-slave replicati...
Usually, there are two options when we develop Li...
This article introduces the CSS Sticky Footer imp...
Preface I was recently reading about MySQL indexe...
Table of contents 1. Check whether the docker env...
If we want to perform batch operations on a type ...
Conversion between rgba and filter values under...
question Recently I encountered a requirement to ...
Introduction to influxDB influxDB is a distribute...
1. Download the mysql tar file: https://dev.mysql...
When installing FileZilla Server on the server, t...
Table of contents Why do we need Docker? Docker d...