Whenever I’ve asked people how to run useEffect once they answer that by saying add an empty array after the function to run it once. Like the following:
useEffect(() => {
console.log("Hi");
}, []);
But that calls the function twice. So the output of the above example in the console would be Hi
twice. But I want Hi
once.
I’ve been using the same normal method for fetching data into my website on the first render.
useEffect(() => {
const fetchData = async () => {
const response = await fetch("https://www.example.com/");
const data = await response.json();
setData(data);
console.log("data fetched");
}
fetchData();
}, []);
The console shows data fetched
twice and that isn’t good for the performance of the website. How can I just fetch the data only once in useEffect.
Aditya Raul is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.