useState()
useState() is a React Hook that allows a functional component to store and update data.Whenever the state changes, React automatically updates the UI.
const [count, setCount] = useState(0);
count -current value
setCount() -updates the value
Project 1 – Toggle Switch
A simple ON/OFF switch.When we click it,OFF becomesn ON
const [isOn, setIsOn] = useState(false);
Initially,false means OFF.
onClick={() => setIsOn(!isOn)}
Here,!false becomes true Next click,!true becomes false So every click changes the state.
Status: {isOn ? "ON" : "OFF"}
If isOn = true React displays ON Otherwise OFF
Project 2 – Live Input Field
let's make an input box. Whenever the user types,Hello, Ezhil updates instantly.
const [name, setName] = useState("");
Initially, name = ""
<input
value={name}
onChange={(e)=>setName(e.target.value)}
/>
Whenever the user types,React calls onChanget the latest value is available in e.target.value If the user types React State becomes
name = "React"
<h3>Hello, {name}</h3>
React automatically updates the screen.
Project 3 – Show / Hide Text
Sometimes we want to display something only when needed. Eg.,Password visibility.
const [show,setShow]=useState(false);
<button onClick={()=>setShow(!show)}>
Conditional Rendering
If show=true React displays Welcome to React!Keep Learning Otherwise,
nothing appears.
Project 4 – Character Counter
Many websites show Characters : 25 while typing. Let's build one.
const [text,setText]=useState("");
<textarea
value={text}
onChange={(e)=>setText(e.target.value)}
/>
Every character updates the state.{text.length}JavaScript strings have a
length property.Hello contains 5 characters.
Project 5 – Country - State - City
const [country,setCountry]=useState("");
const [state,setState]=useState("");
const [city,setCity]=useState("");
Each dropdown has its own state.We use country-state-city package. Country.getAllCountries() returns all countries.Selecting one country loads only its states.Selecting one state loads only its cities.
Top comments (0)