Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
Why is promise response getting call twice in functional component?

I have this code that uses a promises, but my issue is when I console.log the response it prints it 2 times, why is that? Can anyone point me in the right direction? thanks in advance!

import "./App.css";
import { useState } from "react";

function App() {
  const [data, setData] = useState([]);

  let itemsApi = new Promise(function (resolve, reject) {
    setTimeout(() => {
      resolve([
        { grupoId: 1, name: "test1" },
        { grupoId: 2, name: "test2" },
        { grupoId: 1, name: "test3" }
      ]);
    }, 500);
  });

  itemsApi
    .then((res) => {
      console.log(res); // This gets call 2 times, why??
    })
    .catch((error) => {});

  return <div>test</div>;
}

export default App;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

React is free to call your component function as many times as it feels like (and indeed, in Strict Mode it usually calls it twice, to make sure you're not doing bad things with side effects -- as you now are).

Here's an example of how to properly do async data loading using useEffect.

loadData here is just a mock function that takes 500 milliseconds to return data, but could be anything else too.

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function loadItems() {
  const data = [
    { grupoId: 1, name: "test1" },
    { grupoId: 2, name: "test2" },
    { grupoId: 1, name: "test3" },
    { grupoId: 1, name: "test4" },
    { grupoId: 3, name: "test5" },
    { grupoId: 2, name: "test6" },
  ];
  await delay(500);
  return data;
}

function App() {
  const [data, setData] = useState([]);
  React.useEffect(() => {
    loadItems().then(setData);
  }, []); // <- empty dependency array has this effect only run once
  return <div>{JSON.stringify(data)}</div>;
}

export default App;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!