React Component 只能透過資料狀態的改變來更新 UI,而 React 元件有兩種資料來源:
每當 React 偵測到 Props 或 State 有更新時,元件就會重新渲染一次
state 即是元件的狀態,可記住元件的一些資料,透過state來保存、控制以及修改自己可變的狀態。
this.state ⇒ 在class component下設定state初始值
useState ⇒ 在functional component下設定state初始值
useState 會回傳一個array [],裡面包含兩個值,第一個值是 state、第二個值是用來更新 state 的 函式 。每當 state 值改變,就會觸發 re-render (重新渲染)。
const MyComponent = () => {
  const [inputValue, setInputValue] = React.useState('example123@gmail.com');
  return (
    <>
      <input
        value={inputValue}
        onInput={(e) => {
          const newValue = e.target.value;
          setInputValue(newValue);
        }}
      />
      <p>我的email: {inputValue}</p>
    </>
  );
};