Switzz
Switzz

Reputation: 69

Using ComponentDidMount to load data before page renders - React

I am using ComponentDidMount to call data from my database and render page when data is ready. However, i have noticed the speed of my application has reduced when navigating since i have to wait for the data.

This is happening when i have large data in the database i am retrieving. My question is, is there any way of optimizing this, or i just have to render page before data loads ?

Component.JS

componentDidMount()
     {
        this.fetchAllItems();           
     } 

 fetchAllItems(){
        return this.fetchPost().then(([response,json]) => {
         console.log('here now ',response);
         console.log(localStorage.getItem('user_token'))
           if(response.status === 200)
           {   

           }
        })
     }



     fetchPost(){
        const URL = 'http://localhost:8000/api/';
        return fetch(URL, {method:'GET',headers:new Headers ({
           'Accept': 'application/json',
           'Content-Type': 'application/json',
              })})
        .then(response => Promise.all([response, response.json()]));
     }

Upvotes: 0

Views: 14396

Answers (3)

Astrit Spanca
Astrit Spanca

Reputation: 724

In your case all the optimization must be done in the backend.

But if there is something that can be done in React is using Should Component Update as previous comment mentioned.

Upvotes: 0

Rohit Kashyap
Rohit Kashyap

Reputation: 1592

Have you tried the shouldComponentUpdate lifecycle method? This method accepts nextProps (new or upcoming props) and nextState (new or upcoming State) parameters. You can compare your next props and state (state preferably in your case) to determine if your component should re-render or not. Fewer re-renders equals to better speed and optimization. that means your pages will load faster. The shouldComponentUpdate method returns a boolean to determine if a page should re-render or not. Read more here. Also, Here's an example:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      value: true,
      countOfClicks: 0
    };
    this.pickRandom = this.pickRandom.bind(this);
  }

  pickRandom() {
    this.setState({
      value: Math.random() > 0.5, // randomly picks true or false
      countOfClicks: this.state.countOfClicks + 1
    });
  }

  // comment out the below to re-render on every click
  shouldComponentUpdate(nextProps, nextState) {
    return this.state.value != nextState.value;
  }

  render() {
    return (
      <div>
        shouldComponentUpdate demo 
        <p><b>{this.state.value.toString()}</b></p>
        <p>Count of clicks: <b>{this.state.countOfClicks}</b></p>
        <button onClick={this.pickRandom}>
          Click to randomly select: true or false
        </button>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

Upvotes: 0

ThanhEngineer
ThanhEngineer

Reputation: 1339

Try to use axios to make call to API asynchronously, after it's done, just update your response data to state. No need to wait your page is finished loading or not, react will render by following changes of state value.

import React from 'react';
import axios from 'axios';

export default class MovieList extends React.Component {
  state = {
    movies: []
  }

  componentDidMount() {
    axios.get(`http://localhost/movies`)
      .then(res => {
        const movies = res.data;
        this.setState({ movies: movies });
      })
  }

  render() {
    const {
       movies
    } = this.state;
    return (
      <div>
          <ul>
          { movies.map(movie => <li>{movie.name}</li>)}
          </ul>
      </div>
    )
  }
}

Upvotes: 2

Related Questions