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

149
Visualizações
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 Respostas
Responde à pergunta

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 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