preface

In our daily development, we often encounter a scenario where an asynchronous request for data is performed after the component is loaded, and only one request for data is performed during the first rendering to initialize the page. At this time, useEffect hook must come to mind

useEffect( () => {}, [] )

https://react.docschina.org/docs/hooks-effect.html website Api

This article mainly wants to talk about the dependency of useEffect. It is not necessary to talk about the basic use of useEffect. You can check the official website API.

Going back to the prologue question, if I wanted to execute effect only once, wouldn’t I just rely on giving an empty array?

const getTableData = () = > {
   Api.get()...
}
useEffect(() = > {
  getTableData()
}, []}
Copy the code

This does fulfill our required functions, but it is not officially recommended to do so. 😂). Lint will actually report an error if the related lint is installed in the project, like this

See, he told me that I was missing a dependency, which means that the useEffect hook actually relies on getTableData.

All right, I’ll add it to your list

const getTableData = () = > {
   Api.get()...
}
useEffect(() = > {
  getTableData()
}, [getTableData]}
Copy the code

GetTableData is new and different every time a component is updated. What’s the use of throwing it in a dependency? Finches eat without eggs

What do you want me to do?? Let me write in rely on, I write inside and not work 😭. In that case, well, I don’t depend on you. I’ll do it myself.

useEffect(() = > {
    const getTableData = () = > {
       Api.get()...
    }
    getTableData()
}, []}
Copy the code

UseEffect will not report any errors if it is executed once without dependencies. But there are limitations. What if I use this function somewhere else? If you add, delete, change, or check the table, it doesn’t work, because you still have to request the latest data again.

There’s another way, and lint already tells us what to do with it, to drop it into a useCallback

useCallback(() => {},[])

const getTableData = useCallback(() = > {
    Api.get()...
},[xxx])
useEffect(() = > {
    getTableData()
},[getTableData])
Copy the code

This fixes the problem, and useCallback can also set dependencies. If useCallback’s dependencies remain unchanged, getTableData will not be executed again. The function returned by useCallback does not accept arguments. .

So according to the official website, the best use of useCallback is to optimize performance as a parent component transfer function? ! Next time take a look at the best use of useCallback 😁, if there are any improper place welcome criticism, the most important thing is to learn with you, share!!