Closed GOI17 closed 10 months ago
Dan Abramov links to the same article in his example of how to fetch data with useEffect: https://overreacted.io/a-complete-guide-to-useeffect/#moving-functions-inside-effects -- I believe his concern is not that this is possible, but rather that people may do it in a way that hides dependencies from react.
This is the modified example that he gives:
function SearchResults() {
const [query, setQuery] = useState('react');
useEffect(() => {
function getFetchUrl() {
return 'https://hn.algolia.com/api/v1/search?query=' + query; }
async function fetchData() {
const result = await axios(getFetchUrl());
setData(result.data);
}
fetchData();
}, [query]); // ✅ Deps are OK
// ...
}
He also cites the same article that I have here, but we can update to his "complete guide for react". Pull requests welcome. Also, recently he said the following:
one way to think about it is that useEffect is a way to synchronize React with some external system (network, subscription, DOM). if you don’t have any external system and just try to manage your data flow with useEffect, you’re gonna have all these problems.
Emphasis added, citation: https://twitter.com/dan_abramov/status/1501737272999301121
So, it appears that fetching data is still one of the valid use cases for useEffect. The outcome, in relation to this proposal, is the same though. The point of this section is to show how async behavior is sometimes hidden by frameworks. Unlike other frameworks, react seems to only do this for data, and not for modules themselves. Vue and other frameworks allow lazy loading.
As Dan Abramov said many times the useEffect hook is not for data fetching, react don't have a hook for that. You can use SWR, React Query or your own fetcher around suspense but useEffect is not for that.
react has a hook "use effect" -- but this is primarily for data