The timing of the initialization operation

In general, business components often encounter scenarios where they need to initiate Ajax requests to retrieve business data and perform initialization operations. In the use of class component programming, we can in the class component provides the life cycle of a hook function (such as componentDidMount, constructor, etc.) to carry out the operation. If function Component does not have lifecycle hook functions after React hooks, what about this initialization? You can’t use class Component every time you encounter this scenario, can you?

Solution: Use useEffect(to find out what useEffect is, click here)

UseEffect, perform the work of a have side effects, you can use it as a componentDidMount, componentDidUpdate, and componentWillUnmount collection. 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 the request and perform the initialization
    }
    The second parameter must be passed to the empty array if you only want to initialize the data once at render time.
    useEffect(() = >{ initData(); } []);return (<div></div>)}Copy the code

And notice that this isuseEffectThe second argument to theAn empty array, so it is equivalent to only incomponentDidMount“Is executed. If you don’t pass the second argument, this is equivalent tocomponentDidMountandcomponentDidUpdate

Do some cleanup

In actual development, we often encounter some side effects, such as rotation training operation (timer, rotation training request, etc.), using the browser’s native event listening mechanism instead of the React event mechanism (in this case, users need to take the initiative to cancel event listening when components are destroyed), etc. When programming with Class Component, we usually clean up componentWillUnmount. When using React hooks, what do we do?

Solution: Use the return value of the first argument to useEffect (return)

If useEffect returns the function as the first argument, React will execute the function to do some cleanup before each new effect is executed. Therefore, we can use it to perform some cleanup operations.

Example: For example, if we want to make a TWO-DIMENSIONAL code component, we need to constantly poll the background to query the status of scanning the two-dimensional code based on the incoming userId. In this case, we need to clean up the polling operation when the component is unmounted. The code is as follows:

import React, { useEffect } from 'react'

export function QRCode(url, userId) {
  // Query scan status according to userId
  const pollingQueryingStatus = async () => {
  }
  // Cancel polling
  const stopPollingQueryStatus = async() => {
  }

  useEffect(() = > {
    pollingQueryingStatus();

    returnstopPollingQueryStatus; } []);// Generate a QR code based on the URL
  return (<div></div>)}Copy the code

However, sometimes we may need to perform multiple cleanup operations. Using the above example, we need to execute a new query when the user passes in a new userId, and we also need to clean up the old polling operation. Let’s think about what we can do. UseEffect’s second parameter is the key to triggering effects. If the user passes in a second parameter, effects will only be triggered when the value of the second parameter changes (and the first rendering). Therefore, we just need to change the above code:

mport React, { useEffect } from 'react' export function QRCode(url, Const pollingQueryingStatus = async() => {} const stopPollingQueryStatus = async() => {} // We just add userId useEffect(() => {pollingQueryingStatus(); return stopPollingQueryStatus; }, [userId]); Return (<div></div>)}Copy the code

We simply add a userId to the second useEffect. In this case, each change to the userId will trigger stopPollingQueryStatus before effects.

Reference: Coke is good but not fat