React fetching data before rendering in 2020
Tags: react, 2020
Published: 2020-05-10 15:23:03


TLDR:
Do not fetch data in `ComponentWillMount`, do it in `ComponentDidMount`

There are few use cases in React project where you think you need to fetch  data before rendering.

When you quickly google *'fetching data before first rendering in React'*, this is the first [answer](https://stackoverflow.com/questions/30929679/react-fetch-data-in-server-before-render) that popped up from StackOverlflow. 

The most voted answer which suggests to do in <code>componentWillMount()</code>, a method fired off before render() in React lifecycle will be completely [deprecated](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html) in React v17 (as of current writing on 5/10/2020 React is at version 16.13.1).

The mechanism of data lifecycle in React is complex enough that Facebook created [Relay](https://relay.dev/docs/en/experimental/step-by-step) and [Suspence](https://reactjs.org/docs/concurrent-mode-suspense.html) in React 16.6 to address it. Read the second article to fully understand all use cases.

Here I present some issues that one <code>think</code> they need to fetch data before rendering, but it's not always the case. 

> It is best to keep your data fetching in componentDidMount() 
(it's okay to have first renders with no data)

Issues:
1. The render gets compile error when data is not found
2. A child component render relies on data response from parent component
3. A child component that has heavy synchronous code relies on data response from parent component

Cases such as 1 and 2. You can implement an if statement to conditionally render based on if your data returned or not.

```jsx

  if( dataIsReturned === true) {
    <RenderYourData/> 
  } else {
   <h1> Loading </h1>
  }


```
or you can simplify by using a ternary statement:

```jsx
 {
  dataIsReturned ? <RenderYourData/> : <h1> Loading </h1>
 }

```

In case #3 usually comes from a design fault to start with. But because it is legacy code, take too much resource to refactor, etc. It  Usually the problem is presented this way.

```jsx

   //start of LegacyChild.js

   let initiator = init(data);

   // 5000 lines of code

   function LegacyChild () = {
     return initiator;
   }

   export LegacyChild;
   //end of LegacyChild.js




   //start of Parent.js
    
   import <LegacyChild/> from './LegacyChild';

   class Parent extends React.Component {

     componentDidMount(){
      fetch()
       .then(this.setState(data));
     }

     render() {
        <LagacyChild/>
     }
   }

   React.render(<Parent/>, document.getElementById('root');
   //end of Parent.js
```
  
Notice two things:

1. LegacyChild.js contains code outside of exported function, in this case there are 5000 lines of synchronous javascript code that is impossible to refactor and they depend on an external data source outside of legacyChild.js. The function LegacyChild's definition depends upon those 5000 lines of code, by leveraging the power of [closure](https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4).

2. In Parent.js, LegacyChild.js is imported at the top of Parent.js, it will result in a compiled error because it reads LegacyChild.js which depends on the data response in Parent component.


In this case you can delay the import of LegacyChild.js by using [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import). 

 ```jsx
 class Parent extends React.Component {

     constructor() {

      this.state = {
        dataIsReturned : false ;
      }
      this.LegacyChild = null;
     } 

     componentDidMount(){
      fetch()
       .then(async (data) => {
          let obj = await import('./legacyChild');
          this.LegacyChild = obj.default;
          this.setState({dataIsReturn : true});
       ).catch( err => console.error(err);)
     }

     render() {
        if dataIsReturned ? <this.LegacyChild/> : <h1> Loading </h1>
     }
   }
  ```
   
   Here we only changed the order of importing legacyChild.js, we still got to fetch the data inside `componentDidMount()`.


Let me know other use case in the comment that I didn't mentioned where you think you are *forced* to fetch data before rendering.