Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks Async Best Practice

Now with use useEffects, there is a substitute for componentDidMount into a React Component with Hooks.

Scenario "initial unique call to a server":

To accomplish this, DependencyList (second argument of useEffect) in useEffect should every time an empty array otherwise the application will send every state change a fetch call to the server.

it means, this is the best practice to getData

useEffect(() => {
  console.log("useEffect, fetchData here");
}, []);

Is it best practice, to use [] as DependencyList param to disable server requesting every state changing?

Link to github https://github.com/facebook/react/issues/14326

like image 973
R J Funnel404 Avatar asked Feb 08 '19 16:02

R J Funnel404


Video Answer


1 Answers

Yes. This is the best approach.

From the react docs:

Passing in an empty array [] of inputs tells React that your effect doesn’t depend on any values from the component, so that effect would run only on mount and clean up on unmount; it won’t run on updates.

useEffect is a very powerful, and my favorite, hook. You can monitor one or more variables for state changes by passing them into the second parameter array, or you can just listen for mounting and unmounting with the approach that you're using.

like image 52
Don Brody Avatar answered Sep 29 '22 17:09

Don Brody