DEV Community

Cover image for How to fetch data before rendering in React JS
Sergio Holgado
Sergio Holgado

Posted on • Edited on

How to fetch data before rendering in React JS

In React.js, you can fetch data before mounting and components using various techniques, in order to display components require the fetched data before being displayed, the data must be fetched before mount, mounting means putting elements into the DOM. React has four built-in methods that gets called, in this order, when mounting a component: constructor() getDerivedStateFromProps() render().

React lifecycle

Here are a few common approaches depending on whether your react app is class based or functional:

Functional Components App

A functional component in a React app is a JavaScript function that returns JSX (JavaScript XML) to define the structure and behavior of a user interface element. It is a simpler and more lightweight alternative to class components. Functional components allow you to write reusable and stateless code by using hooks like useState and useEffect to manage component state and lifecycle effects. They are widely used in modern React development due to their simplicity and readability.

If your app is functional components based, use the useEffect hook, and fetch your data within the hook which is executed, before mount.



import React, { useEffect, useState } from 'react';

function MyComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch('your-api-endpoint');
      const result = await response.json();
      setData(result);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  // Render the component using the fetched data
  return <div>{/* Render your component with the fetched data */}</div>;
}


Enter fullscreen mode Exit fullscreen mode

Class-Based React App

For class components, you can also use async/await inside the componentDidMount method to fetch data, but it won't fetch the data before rendering, instead it will trigger a re-render, note that the method componentWillMount has been deprecated. the only way to fetch data before rendering is using the useEffect hook. Nevertheless using componentDidMount can be ideal for certain cases.



import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData = async () => {
    try {
      const response = await fetch('https://api.example.com/data');
      const jsonData = await response.json();
      this.setState({ data: jsonData });
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  render() {
    const { data } = this.state;

    return (
      <div>
        {/* Render your component using the fetched data */}
      </div>
    );
  }
}

export default MyComponent;


Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
nhanhoang8195 profile image
NhanHoang

I'm not sure what term of rendering you are referring to, but I believe that useEffect will be run after component is mounted, it means that the effect will be run after browser paint.

Collapse
 
sergioholgado profile image
Sergio Holgado • Edited

Yes, you are right, I used the term rendering as an oversimplification for SEO purposes, I'll correct it right now, thanks for the the feedback!

Collapse
 
kuetabby profile image
Ivan

agreed