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> </> ); } 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
没有评论:
发表评论