UseEffect, as the name suggests, is to do something that has side effects, and you can think of it as a set of componentDidMount, componentDidUpdate, and componentWillUnmount. Its function declaration is as follows

useEffect(effect: React.EffectCallback, inputs? : ReadonlyArray<any> | undefined)Copy the code

🌰

import React, {useEffect} from 'react' export function BusinessComponent() {const initData = async () => {// Initiate request and perform initialization} // To initialize, note that if you only want to initialize the data once at render time, the second parameter must be passed to the empty array. useEffect(() => { initData(); } []); return (<div></div>); }Copy the code

Note that the second argument to useEffect here must be passed to the empty array so that it is equivalent to executing only when componentDidMount. If you don’t pass the second argument, it’s equivalent to componentDidMount and componentDidUpdate

Do some cleanup

Because in the actual development process, we often meet need to do some side effects scenarios, such as polling operation (timer, polling requests, etc.), use the browser native events to monitor events rather than react mechanism (in this case, the component destroyed, requires the user to take the initiative to go to cancel the event listeners), etc. ComponentWillUnmount or componentDidUnmount. How do you fix react hooks?