3 ms·
A recent thing which has been rubbing me the wrong way in React has been the exhaustive dependencies for useEffect and other hooks. Sure, in the case someone w
by tekkk 6y ago
A recent thing which has been rubbing me the wrong way in React has been the exhaustive dependencies for useEffect and other hooks.
Sure, in the case someone would alter say the function provided as props it should be included in the dependency array. Yet in most cases, such as the example #3 in the article, this would not happen (or be even desired). Rather, if it did it would be a bug and an appropriate error would better.
So if you wanted to adhere to the strict CRA linter's exhaustive dependencies rule, you should add the fetchData function as a dependency. Or if you moved the whole function inside the useEffect, then the onSuccess. Which makes even less sense now that I've written it down.
- brlewis 6y agoThere is no harm in adding something to the dependency array that you don't expect to ever change. The linter is your friend; make its job easier.
- tekkk 6y agoWell, I disagree. As I said in my other reply - if the intention is that the prop is immutable there should be an error instead of very strange recomputation of the useEffect hook.
- cellar_door 6y agoI mean, onSuccess could change. And as you suggested, creating the extra callback is redundant. const fetchData = () => { setLoading(true); callApi() .then((fetchedData) => { setData(fetchedData); onSuccess(); }) .catch((err) => setError(err)) .finally(() => setLoading(false)); }; useEffect(() => { fetchData(); }, []); becomes useEffect(() => { setLoading(true); callApi() .then((fetchedData) => { setData(fetchedData); onSuccess(); }) .catch((err) => setError(err)) .finally(() => setLoading(false)); }, [onSuccess]);
- tekkk 6y agoSure it could but if the intention of the developer is to run the API call only once per mount, never otherwise, it would be more appropriate to throw an error instead of just adding pointless dependencies. It just seems like a dumb overhead which goes against the actual goals of the developer.