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().
Functional Components App
If your app is functional components based, use the
useEffect hook, and fetch your data within the hook which is executed, before mount.
Here are a few common approaches depending on whether your react app is class based or functional:
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.