2021年3月23日星期二

Why alert in useEffect run before console in return statement in a functional component?

According to react docs, If we don't specify the second argument in the useEffect hook it will behave like componentDidMount and componentDidUpdate

By using useEffect Hook, you tell React that your component needs to do something after render - react docs

That means in both cases useEffect will run after the initial render and after the update.

import { useState, useEffect } from "react";    export default function App() {    const [checked, setChecked] = useState(false);      useEffect(() => {      console.log("useEffect statement");      alert("Alert in useEffect hook");    });      function onChecked() {      setChecked((state) => {        return !state;      });    }      return (      <>        {console.log("return statement")}        {alert("Alert in return hook")}        <input value="checked" onChange={onChecked} type="checkbox" />        <h1> {checked ? "checked" : "Not-checked"} </h1>      </>    );  }  

codesandbox

I was expecting the result to be in the following sequence:

  • console data from the return statement
  • alert in the return statement
  • console data from useEffect hook
  • alert in useEffect hook

But what I got is in the following sequence:

  • alert in the return statement
  • alert in useEffect hook
  • console data from the return statement
  • console data from useEffect hook
https://stackoverflow.com/questions/66773773/why-alert-in-useeffect-run-before-console-in-return-statement-in-a-functional-co March 24, 2021 at 10:05AM

没有评论:

发表评论