When starting React, understanding useState only through definitions can feel confusing. The easiest way to learn it is by building small projects.
In simple words:
useState allows React components to store data and update the UI when that data changes.
Syntax:
const [state, setState] = useState(initialValue);
Where:
- state → current value
- setState → function used to update value
- initialValue → starting value
Example 1: Show / Hide Password
A common beginner project is password visibility toggle.
import { useState } from "react";
function App(){
const [show,setShow]=useState(false);
return(
<>
<input
type={show ? "text":"password"}
/>
<button
onClick={()=>setShow(!show)}
>
{show ? "Hide":"Show"}
</button>
</>
)
}
export default App;
How it works
Initially:
show = false
Therefore:
input type = password
Password appears hidden.
When button clicked:
setShow(!show)
If:
show = false
Then:
!show
↓
true
React updates state.
Component re-renders.
Now:
input type = text
Password becomes visible.
Flow:
Button Click
↓
State Change
↓
Re-render
↓
Updated UI
This example teaches:
- Boolean state
- Toggling values
- Conditional rendering
- Re-rendering
Example 2: Todo App
Todo App is one of the best projects to practice state management.
Features:
- Add task
- Edit task
- Delete task
import { useState } from "react";
function App(){
const [task,setTask]=useState("");
const [todos,setTodos]=useState([]);
const [editIndex,setEditIndex]=useState(null);
function addTodo(){
if(task==="") return;
if(editIndex!==null){
const updated=[...todos];
updated[editIndex]=task;
setTodos(updated);
setEditIndex(null);
}
else{
setTodos([...todos,task]);
}
setTask("");
}
function deleteTodo(index){
const filtered=
todos.filter((_,i)=>i!==index);
setTodos(filtered);
}
function editTodo(index){
setTask(todos[index]);
setEditIndex(index);
}
return(
<>
<input
value={task}
onChange={(e)=>setTask(e.target.value)}
/>
<button onClick={addTodo}>
{editIndex!==null ? "Update":"Add"}
</button>
<ul>
{
todos.map((item,index)=>(
<li key={index}>
{item}
<button
onClick={()=>editTodo(index)}
>
Edit
</button>
<button
onClick={()=>deleteTodo(index)}
>
Delete
</button>
</li>
))
}
</ul>
</>
)
}
export default App;
Adding Tasks
Suppose:
task = Study React
Click:
Add
This line runs:
setTodos([...todos,task])
React creates:
["Study React"]
UI updates automatically.
Editing Tasks
Click:
Edit
Current value goes into input.
Change text.
Click:
Update
Array value changes.
UI updates again.
Deleting Tasks
This code runs:
todos.filter((_,i)=>i!==index)
Selected task removed.
New array created.
UI updates.
What Did We Learn?
These examples teach an important React rule:
State Changes
↓
Component Re-renders
↓
UI Updates
Simple rule:
If data changes and UI should update, use state.
That is why useState becomes one of the first and most important hooks in React.
Top comments (0)