Today, I learned more about the useState Hook in React. I practiced increment, decrement, and reset operations. I also worked on two scenarios: a toggle button and an input field.
1. useState Hook
The useState Hook allows us to store and update data in a functional component.
Syntax
const [state, setState] = useState(initialValue);
state stores the current value.
setState updates the value.
initialValue is the starting value.
I also learned that component names should start with a capital letter, such as ToggleButton or NameInput.
A functional component is a JavaScript function that returns JSX.
2. Toggle Button: ON and OFF
I created a button that switches between ON and OFF.
`import { useState } from "react";
function Toggle() {
const [ toggle,settoggle] = useState("OFF");
function togglebtn(){
if(toggle === "OFF"){
settoggle("ON");
}
else{
settoggle("OFF");
}
}
// toggle === "OFF" ? settoggle("ON"): settoggle("OFF");
return (
<div>
<button onClick={togglebtn}> {toggle } </button>
</div>
)
}
export default Toggle;
`
- I used a Boolean state (true or false).
- The initial value is false, so the button starts at OFF.
- Clicking the button changes the state to its opposite value.
- React updates the UI when the state changes.
3. Input Field: Displaying a Name
I also practiced taking a name from an input field and displaying a greeting.
`import { useState } from 'react';
function Greeting() {
const [userinput, setuserInput] = useState("");
let user_input = "";
function greet() {
setuserInput("Hello" + user_input);
}
function getInput(event) {
user_input = event.target.value;
setuserInput(event.target.value);
}
return (
Greet me
{userinput}
</div>
)
}
export default Greeting;`
- What I understood:
- useState('') starts with an empty string.
- value={name} connects the input to the state.
- onChange runs when the user types.
- event.target.value gets the text entered by the user.
- setName() updates the state, and React displays the new greeting.
Why use useState instead of a normal variable?
A normal variable does not automatically tell React to render the component again when its value changes. Using useState lets React keep track of the value and update the UI when the state changes.
What I Learned Today
- The syntax of the useState Hook.
- How to increment, decrement, and reset values.
- How to create a toggle button using Boolean state.
- How to store input values using useState.
- How state updates cause React to update the UI.
- Why functional components and reusable component names are important.
Top comments (0)