Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

291
Visualizações
why onload function is being called twice, though component is rendering once?

I am having a simple react component, the fire is printed once, but injectWindowInterval is called twice event though i am setting flag value, why is it so?

const Header = () => {
  let flag = true;
  
  console.log("fire");  

  function injectWindowInterval() {
    if (flag && window.google) {
      flag = false;
      console.log(window.google);
    }
  }

  const script = document.createElement("script");
  script.src = "https://accounts.google.com/gsi/client";
  script.onload = injectWindowInterval;
  script.async = true;
  document.querySelector("body")?.appendChild(script);

  return (
    <div className="header">
      <h3 className="header__title">RE</h3>
    </div>
  );
};

Update: for some reason, the script is appending twice in body.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In some cases function are called on render when they are defined. One common example is with onClick methods for buttons

<button onClick={onClickFunction}>Click me</button> //fires on render
<button onClick={()=>onClickFunction()}>Click me</button> //no fire on render, works well

So maybe try

const Header = () => {
  let flag = true;
  
  console.log("fire");  


  const script = document.createElement("script");
  script.src = "https://accounts.google.com/gsi/client";
  script.onload = () => {
    if (flag && window.google) {
      flag = false;
      console.log(window.google);
    }
  };
  script.async = true;
  document.querySelector("body")?.appendChild(script);

  return (
    <div className="header">
      <h3 className="header__title">RE</h3>
    </div>
  );
};
about 4 years ago · Juan Pablo Isaza Relatório

0

If you are rendering the Component in <React.StrictMode>, the component will render twice for sure in development mode. I tried rendering above component(Header) and the fire is logged in the console twice so do the script tag appended twice. Here is the console Output

Note : Also note that React renders component twice only in development mode. Once you build the app the component will be rendered only once.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda