Skip to content
Advertisement

Prompt Repeats Twice When Page Renders (Undesirable) React.js JavaScript

When I have a basic prompt setup such as

var tag = prompt("Enter Tag")

or

  useEffect(() => {
    tagP = window.prompt('Enter tag') 
    console.log(tagP) 
});

The prompt repeats itself twice when the page loads. I only want this to happen once. I tried initializing the prompt with a loop without useEffect and I get the same results. When I try to initialize the prompt with a loop inside useEffect the prompt only shows up once as desired but the value for tagP is rendered as the initial value and not the new prompt value. I also get a warning suggesting that I use useRef. The warning message is below. I just would like to know why the prompt is repeating. If possible, I would like to just have a simple prompt statement without a loop or useEffect. I’ve tried with multiple environments and the results are constant. I appreciate all ideas! Thank you for your time!

“Assignments to the ‘tagP’ variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the ‘.current’ property. Otherwise, you can move this variable directly inside useEffect.es”

 var tagP = "Example"
  useEffect(() => {
    if (tagP === "Example") {
      tagP = window.prompt('Enter tag') 
      console.log(tagP) }
  });

Advertisement

Answer

You should give an empty array as second parameter to useEffect,

useEffect(() => {
    tagP = window.prompt('Enter tag') 
    console.log(tagP) 
}, []);

Prompt appearing twice can also be to react strict mode

React StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them.

You can remove the StrictMode and verify once.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement