State သည် component အတွင်းက ပြောင်းလဲနိုင်တဲ့ data ပါ။ Button နှိပ်ပြီး count တိုးတာ၊ input ထဲစာရိုက်တာ၊ modal ဖွင့်/ပိတ်တာ၊ cart item ထည့်တာတွေမှာ state ကိုသုံးပါတယ်။ State ပြောင်းသွားရင် React က component ကိုပြန် render လုပ်ပြီး UI ကို update လုပ်ပေးပါတယ်။
jsx
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function increase() {
setCount(previousCount => previousCount + 1);
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={increase}>Click me</button>
</div>
);
}`count` ကလက်ရှိတန်ဖိုး၊ `setCount` က update လုပ်ပေးတဲ့ function ပါ။ Button နှိပ်တိုင်း `increase` function run ဖြစ်ပြီး count တစ်ခုတိုးပါတယ်။
You should see
Button ကိုနှိပ်တိုင်း `You clicked 1 times`, `2 times` စသဖြင့် UI ထဲက number တိုးသွားမယ်။Info
`setCount(count + 1)` လည်းရပေမယ့် အရင် state ကိုမှီပြီး update လုပ်တဲ့အခါ `setCount(previous => previous + 1)` ပုံစံကပိုကောင်းပါတယ်။