I am writing code so that before the data is loaded from DB, it will show loading message, and then after it is loaded, render components with the loaded data. To do this, I am using both useState hook and useEffect hook. Here is the code:
The problem is, useEffect is triggered twice when I check with console.log. The code is thus querying the same data twice, which should be avoided.
Below is the code that I wrote:
import React from ‘react’;
import ‘./App.css’;
import {useState,useEffect} from ‘react’;
import Postspreview from ‘../components/Postspreview’
const indexarray=[]; //The array to which the fetched data will be pushed
function Home() {
const [isLoading,setLoad]=useState(true);
useEffect(()=>{
/*
Query logic to query from DB and push to indexarray
*/
setLoad(false); // To indicate that the loading is complete
})
},[]);
if (isLoading===true){
console.log(“Loading”);
return
}
else {
console.log(“Loaded!”); //This is actually logged twice.
return (
)}
);
}
}
export default Home;
Why it is called twice, and how to fix the code properly?
In the useEffect, you probably have other side effects that make the component rerender but will only be called once.’ UseFfect(()=> /* Query logic */ console.log(’i fire once’); .\n\nIf the log \”i fire once\” is triggered more than once it triggers your problem is one of 3 things, your component is in the page a couple of times and each one will mount and run the useEffect One is unmounting and remount on its first render. This may be something like an \”key\” change that will be higher up the tree up until it renders only once. then you should be able to find the cause or the React.Strict mode is on display.\n\nStrictMode uses twice (on dev but not production) components to detect any problems with your code and warn you of them (which can be very useful).\n\nThis answer was written by @johnhendirx & @rangfu. If this was your problem, please follow the link and love him. if you\’re having problems because it is usually meant that you are not using use of useEffect for its intended use. There are good details about this in the docs you can read here.