Where to Fetch Data: componentWillMount vs componentDidMount

Where to Fetch Data: componentWillMount vs componentDidMount  #ReactJS #JavaScript

  • There are two common places to fetch data:

    And just so we’re clear, the function is never a good place to fetch data – or to do anything that’s asynchronous, that changes state in some way, or that causes side effects.

  • This function is called right before the component’s first render, so at first glance it appears to be a perfect place to put data fetching logic.
  • This means the component will render with empty data at least once.
  • In practice, is the best place to put calls to fetch data, for two reasons:

    Using DidMount makes it clear that data won’t be loaded until after the initial render.

  • If you’re still not sure of the best way how to actually make the AJAX call and load data, read my post AJAX Requests in React.

When you need to fetch some data for a React component, where do you do it?

@ReactiveConf: Where to Fetch Data: componentWillMount vs componentDidMount #ReactJS #JavaScript

This question comes up all the time.

There are two common places to fetch data:

function is never a good place to fetch data – or to do anything that’s asynchronous, that changes state in some way, or that causes side effects.

Let’s look at the two common options and the pros and cons of each.

This function is called right before the component’s first render, so at first glance it appears to be a perfect place to put data fetching logic.

There’s a “gotcha,” though: An asynchronous call to fetch data will not return before the render happens. This means the component will render with empty data at least once.

somehow. The right way to handle this is to setup the component’s initial state so that it’s valid for rendering.

, so if you already have a constructor, you can just put the code there.

is called, the component has been rendered once.

is the best place to put calls to fetch data, for two reasons:

I hope this clears up the question of where to load data. If you’re still not sure of the best way how to actually make the AJAX call and load data, read my post AJAX Requests in React.

Where to Fetch Data: componentWillMount vs componentDidMount