---
# System prepended metadata

title: useState and useEffect

---

# useState and useEffect

```javascript=
import React, { useState, useEffect /* effect hock */} from "react";

function User() {
    // componentDidMount, [] array define this is didmount
    useEffect(() => {
      alert("function added")
    }, [])
  
  // componentWillUnmount
  useEffect(() => {
    return () => {
      alert("function removed")
    }
  }, [])
  
  useEffect(() => {
    const intervalId = setInterval(() => {
      document.title = `${new Date().toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true })}`;
    }, 1000);
 
    return () => {
      document.title = "Time stopped.";
      clearInterval(intervalId);
    }
  }, [])
  
  return (
    <div>
      User
    </div>
  )
}

function App() {
  const [num, setNum] = useState(0);
  const [buttonValue, setButtonValue] = useState("myuser");
  const [user, setUser] = useState(false);
  
  // componentDidMount, [] array define this is didmount
  useEffect(() => {
    setNum(num + 1)
  }, [])
  
  // componentDidUpdate
  useEffect(() => {
   setNum(num + 1)
  }, [buttonValue])

  
  const updateButton = () => {
    setButtonValue("myuser update")
    setUser(!user);
  }
  
  return (
    <div>
      { num }
      <br />
      <button onClick={updateButton}>update trigger</button>
      <br />
      { buttonValue }
      { user && <User /> }
    </div>
  );
}


ReactDOM.render(<App />, document.querySelector("#mountNode"))
```