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

87
Vistas
how to make a custom hook being executed once globally

I have a hook that adds a header tag in order to load a script, but in case two components are using it, the hook could fall into the case that the header is added twice.

There are several ways to avoid this. Two of them could be:

  1. Use a provider, not a hook that several components could call. Actually I don't want this, I want a hook because at most two components will use it, and in some cases I don't even need it;
  2. The hook calls a function called const addHeaderTag = () => {...}. I could add a property to it and check if the function is called just once, otherwise return silently. It could be safe because the function is defined by me and I control the function object, plus javascript is monothread and concurrency is out of scope;
  3. I could add an id to the header so as to check if it's on the DOM already. I'd avoid it in order to not access the DOM too much

Do you see other better ways? Do you see any problem to the solutions I had in mind?

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

0

A solution for this would be using a variable outside of your custom hook to check whether or not your hook is already called

import { useEffect } from "react";

let isCalled = false;

export const useOnce = () => {
  useEffect(() => {
    if (!isCalled) {
      // do this only once, call your function here
      console.log("hey there");
      isCalled = true;
    }
  }, []);

  return isCalled;
};

The reason this works is because when you import the same module multiple times, the code in that module is still only evaluated once. That means isCalled in this case is only initialized once, so we can depend on it to check/set the value accordingly for the entire app.

Live example

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