Now with use useEffect
s, 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With