Re:Common mistakes writing React components with hooks
by cellar_door on Tuesday July 21, 2020 @01:03PM
(#23908596)
I 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]);
Re:Common mistakes writing React components with hooks
by tekkk on Tuesday July 21, 2020 @05:46PM
(#23911333)
Sure 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.
Re:Common mistakes writing React components with hooks
by brlewis on Tuesday July 21, 2020 @12:54PM
(#23908485)
There 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.
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.