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
Data is the core asset of an enterprise and one o...
Table of contents Global Registration Partial Reg...
ScreenCloud is a great little app you didn’t even...
CSS plays a very important role in a web page. Wi...
Preface Introduction Lombok is a handy tool, just...
statement : This article teaches you how to imple...
The installation of mysql5.7.18zip version on Win...
Services provided by NFS Mount: Enable the /usr/s...
TypeScript Bundling webpack integration Usually, ...
Table of contents Data Brokers and Events Review ...
Table of contents 1. Error message 2. Cause of er...
Table of contents background Purpose Before split...
This article shares with you how to use the Vue s...
Preface: The Linux host is relatively easy to han...
1 Requirements Overview The data of multiple tabl...