skip to Main Content

Let’s consider this to be the component:

const Alert = () => {
        useEffect(() => {
            alert("hello");
        }, []);
        return <div>Alert</div>;
    };

My understanding is that useEffect runs after the browser has painted.

But in this code, why does the alert pop up before the browser is painted completely?

NOTE: If it does not happen the first time, try refreshing it.

2

Answers


  1. can use requestAnimationFrame like this –

    const Alert = () => {
        useEffect(() => { 
            requestAnimationFrame(() => {
                alert("hello");
            });
        }, []);
    
        return <div>Alert</div>;
    };
    
    Login or Signup to reply.
  2. It is being understood that useEffect runs after the browser has been painted.

    This assumption isn’t quite right. The documentation states:

    When your component is added to the DOM, React will run your setup function.

    This doesn’t mean the whole application has rendered. It can even run before the DOMContentLoaded event.

    As alert() is a blocking function, it will halt the execution of the rest of your code until the message is closed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search