So let say I have one home page with 3 tabs, "All", ‘Sci-fi’,"Comedy".I am calling the child component in the home page and rendering the respected data. What is happening is that when user visit for the first time tab is selected as "All". My child component is making same api call twice.How to prevent it.
import React from 'react';
import ChildComponent from './ChildComponent';
function Home() {
return (
<div>
<h1>Home Component</h1>
<ChildComponent />
</div>
);
}
export default Home;
import React, { useState, useEffect } from 'react';
function ChildComponent() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
<div>
<h2>Child Component</h2>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default ChildComponent;
2
Answers
I see your issue, I have a few solutions here, let’s see if any of them can be applied to your project:
Try removing React.Strictmode in your main.jsx.
you would go from:
<React.StrictMode> <App/> </React.StrictMode>
to:
<App/>
, because React.Strictmode executes twice for some reason