惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
Y
Y Combinator Blog
Martin Fowler
Martin Fowler
D
Docker
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
L
LangChain Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 三生石上(FineUI控件)
博客园_首页
量子位
罗磊的独立博客
Blog — PlanetScale
Blog — PlanetScale
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
宝玉的分享
宝玉的分享
Apple Machine Learning Research
Apple Machine Learning Research
D
DataBreaches.Net
I
InfoQ
Engineering at Meta
Engineering at Meta
The Cloudflare Blog
H
Help Net Security
V
V2EX

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Learning React useState Through Practical Examples
Jayashree · 2026-06-03 · via DEV Community
Cover image for Learning React useState Through Practical Examples

Jayashree

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);

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

How it works

Initially:

show = false

Enter fullscreen mode Exit fullscreen mode

Therefore:

input type = password

Enter fullscreen mode Exit fullscreen mode

Password appears hidden.

When button clicked:

setShow(!show)

Enter fullscreen mode Exit fullscreen mode

If:

show = false

Enter fullscreen mode Exit fullscreen mode

Then:

!show

↓

true

Enter fullscreen mode Exit fullscreen mode

React updates state.

Component re-renders.

Now:

input type = text

Enter fullscreen mode Exit fullscreen mode

Password becomes visible.

Flow:

Button Click

↓

State Change

↓

Re-render

↓

Updated UI

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode


Adding Tasks

Suppose:

task = Study React

Enter fullscreen mode Exit fullscreen mode

Click:

Add

Enter fullscreen mode Exit fullscreen mode

This line runs:

setTodos([...todos,task])

Enter fullscreen mode Exit fullscreen mode

React creates:

["Study React"]

Enter fullscreen mode Exit fullscreen mode

UI updates automatically.


Editing Tasks

Click:

Edit

Enter fullscreen mode Exit fullscreen mode

Current value goes into input.

Change text.

Click:

Update

Enter fullscreen mode Exit fullscreen mode

Array value changes.

UI updates again.


Deleting Tasks

This code runs:

todos.filter((_,i)=>i!==index)

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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.