Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

101
Vistas
Function runs two to three times

I have a function in my react app that capitalized the first letter of a word or string that is fetched from an API:

  // Capitalize the first letter of the word/phrase
  const capitalize = (string) => {
    if (string) {
      return string
        .toLowerCase()
        .split(" ")
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(" ");
    } else {
      return;
    }
  };

Note: string is the text that is being fetched from the API. I call the function like so:

capitalize(userInfo.address)

It works as expected but upon logging the results to the console, I realized that it is being run two to three times.

Sandbox: https://codesandbox.io/s/admiring-bose-2qr01j?file=/src/App.js

Is there a way to fix this?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This might be caused by React Strict Mode. Check your index.js. By default React wraps your <App/> component with <React.StrictMode> which intentionally invokes the render method of your inner components two times.

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Just remove it to run functions only once.

root.render(
  <App />
);
about 4 years ago · Juan Pablo Isaza Denunciar

0

It seems that the function is correct, but perhaps, when it is executed after a call to an external data source, an asynchronous call is being made (and possibly more than one), so the capitalize function is executed more than once .

Try to make the function run regardless of where you are calling from.

It could also be that you are executing the function from a code block that is executed more than once, because the function seems to be correct and does not have anything iterative.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda