Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Is it a best practice to use Loader in the main Routes for the API call

AIM: To fetch an api on the web application load on the project level. Because, the application in dependent on this api call. So, If there a place where I can call an api on project level. Please suggest that solution as well.

Sample code:

import "./styles.css";
import { Routes, Route } from "react-router-dom";
import { useEffect } from "react";

export default function App() {

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

  if (isLoading) { // Getting the loader state from 
    //API call
    return <Spinner />;
  }

  return <Routes>
    <Route element={<HomePage />} path="/">
  </Routes>;
}

Doubt: Is this best practice to call an API on the mainroutes and make the spinner load till the API is fetched or else will this cause any side effect. If possible please suggest an alternate solution for this issue.

like image 515
Samben Jerald Avatar asked Dec 18 '25 05:12

Samben Jerald


1 Answers

There're many solutions. But mostly it depends on your project complexity. For really simple projects it's not ideal, but it's okay to make as you did. But I would highly recommend letting the fetch responsibility to your components that really need those data - so you should think about breaking your components

  1. One feature that it's worthy to take a look at is "loader" function from react-router, which is a great feature that you could be using. With this feature you ensure that you're providing the correct fetched data for each of your routes.
  2. You could be using react-query library, because it's a better alternative for useEffect, on the performance level. With "react-query" you fetch data as soon as rendering starts so you don’t have to wait until react loads the entire component
  3. For really complex projects with many API calls, you could use "redux-sagas"
  4. Create a wrapper component that encapsulate this API call. For example, you have 2 types of pages in your application - protected and unprotected routes. You could create a component that receives another Component as prop and are called: ProtectedRoutes which returns 2 components conditionally - UnProtectedPage and Component.
like image 149
William S. Takayama Avatar answered Dec 19 '25 20:12

William S. Takayama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!