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

137
Vistas
What is the correct way to use prompt() inside an useEffect in React.StrictMode so it doesn't run twice?

React.StrictMode renders the page twice to debug purposes. I have a prompt() in a page, which is running twice because of this, and I've been trying to work around it, since I'd like to keep StrictMode.

I tried this, but didn't work:

useEffect(() => {
      let identified = false;
      if (!identified) {
        let pName = prompt("Insert name");
        setPlayerName(pName);
      }
    return () => {
      identified = true;
    }
   }, [])

Also tried this:

const [playerName, setPlayerName] = useState('');
useEffect(() => {
      if (!playerName) {
        let pName = prompt("Insira name");
        setPlayerName(pName);
      }
   }, [])

And this...:

const [playerName, setPlayerName] = useState('');
useEffect(() => {
      if (!playerName) {
        let pName = prompt("Insira name");
        return () => {
          setPlayerName(pName);;
        }
      }
   }, [])

but can't get it right. What's the proper way to do it?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Here you can find info on how to do this:

Effects that should only run once can use a ref.

const didLogRef = useRef(false);

useEffect(() => {
  // In this case, whether we are mounting or remounting,
  // we use a ref so that we only log an impression once.
  if (didLogRef.current === false) {
    didLogRef.current = true;

    SomeTrackingAPI.logImpression();
  }
}, []);

In your scenario:

const didPromptRef= useRef(false);

useEffect(() => {
  if (didPromptRef.current === false) {
    didLogRef.current = true;
    const pName = prompt("Insert name");
    setPlayerName(pName);
  }
}, []);
about 4 years ago · Santiago Trujillo 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