skip to Main Content

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


  1. I see your issue, I have a few solutions here, let’s see if any of them can be applied to your project:

    • Firstly, please make sure you have turned off ReactJS’s StrictMode.
    • Secondly, if each tab of yours calls a different API, create a useState on the Home page.
    function Home() {
      const [tabs, setTabs] = useState('TOP_PAGE')
      return (
        <div>
          <h1>Home Component</h1>
          {tabs === 'TOP_PAGE' && <ChildComponentTopPage /> }
          {tabs === 'SECOND_PAGE' && <ChildComponentSecondPage /> }
        </div>
      );
    }
    • Lastly, if the API for each child component is the same, I recommend placing the API in the parent component, and then passing props to each child component.
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search