Home > database >  Fetching Data outside of Effect in React
Fetching Data outside of Effect in React

Time:10-27

I'm just wondering, is following approach a good way to fetch data? If not, what would be the problems I will face?

const Component = () => {
  const [data, setData] = useState(undefined)
  if (!data) {
   fetchDataAPI('api/mock-data', (data) => setData(data))
  }
}

The data fetching starts by the first render and once it is accomplished, following rerenders wouldn't trigger it anymore.

CodePudding user response:

what would be the problems I will face?

Besides the fact it's kind of an anti-pattern since useEffect was created to handle side effects, you may also end up with multiple requests sent to API. If the component re-renders while data is still undefined (the request is still fetching), the API request will be sent again.

This issue is no longer relevant when using useEffect, since if empty dependency array provided, you are ensured that it will be called only once, even if the component re-renders again.

CodePudding user response:

The issue you would face is that when an initial API call is made in a useEffect with an empty dependency array, the component function knows to only execute the code within the useEffect on the first render, whereas if the code is just executed within the function, an unnecessary check on the data is made every render and if for example, the API request fails and the fetch is not handled correctly, then the request will be run over and over each re-render as the data will remain undefined.

  • Related