Reactive Data - useState
useState is React's most important Hook. In this chapter you will understand React's state management mechanism and implement a category filter feature.
How does React's "reactivity" differ from Vue3?
Vue3 uses ref/reactive to create reactive data, and the view updates automatically when the data changes.
React's approach is different: when you modify state, React re-runs the component function with the new state and renders a new view.
That is the origin of the name React - components "react" to changes in state.
Basic usage of useState
useState is the most basic React Hook, used to add state to function components.
Example
// Import useState by destructuring from react
import
{
useState
}
from
'react'
function
Counter
(
)
{
// useState(initial value) returns an array: [current value, update function]
const
[
count
,
setCount
]
=
useState
(
0
)
function
handleClick
(
)
{
setCount
(
count
1
)
// Update the state, and React will automatically re-render the component
}
return
(
<
div
<
pClick count:
{
count
}
p
<
button onClick
=
{
handleClick
}
1
button
div
)
}
Each time the button is clicked,setCount the value of count is updated; React re-runs the Counter function with the new value, returns new JSX, and the page updates automatically.
React's convention: the state name uses
[something, setSomething]for destructuring. Functions starting with set follow a conventional naming pattern, not a strict requirement, but the entire community writes it this way.
Why can't you modify state directly?
In React, state is read-only. It must be updated via a setter function, not modified directly.
Example
import
{
useState
}
from
'react'
function
ArticleManager
(
)
{
const
[
title
,
setTitle
]
=
useState
(
'Default title'
)
// Wrong way: modify directly
// title = 'New title' // React doesn't know you changed it and won't re-render
// Correct way: update via the setter
function
updateTitle
(
)
{
setTitle
(
'New title'
)
// React knows the state changed and will re-render
}
return
(
<
div
<
p
{
title
}
p
<button onClick
=
{
updateTitle
}
Change the title
button
div
)
}
Behind this is React's immutability (Immutable) principle: do not modify old data, but replace it with new data.
The right way to update arrays and objects
For arrays and objects, you cannot directly push, splice, or modify properties; you must create a new copy.
Example
import
{
useState
}
from
'react'
function
TodoList
(
)
{
const
[
todos
,
setTodos
]
=
useState
(
[
{
id
:
1
,
text
:
'Learn React'
,
done
:
false
}
,
{
id
:
2
,
text
:
'Write blog posts'
,
done
:
true
}
]
)
// Add an item: spread the old array + new element
function
addTodo
(
text
)
{
const
newTodo
=
{
id
:
Date
.
now
(
)
,
text
,
done
:
false
}
setTodos
(
[
...
todos
,
newTodo
]
)
// Create a new array with the spread operator
}
// Modify an item: use map to iterate, find the one to change, and return a new object
function
toggleTodo
(
id
)
{
setTodos
(
todos.
map
(
todo
=>
todo.
id
===
id
?
{
...
todo
,
done
:
!
todo.
done
}
:
todo
)
)
}
// Delete an item: use filter to remove the unwanted one
function
removeTodo
(
id
)
{
setTodos
(
todos.
filter
(
todo
=>
todo.
id
!==
id
)
)
}
return
(
<
ul
{todos.
map
(
todo
=>
(
<
li key
=
{
todo.
id
}
onClick
=
{
(
)
=>
toggleTodo
(
todo.
id
)
}
{
todo.
done
?
<
s
{todo.
text
}
s
:
todo.
text
}
li
)
)
}
ul
)
}
| Operation | Incorrect Writing | Correct Writing |
|---|---|---|
| add | arr.push(item) |
setArr([...arr, item]) |
| Modify | arr[0] = newVal |
setArr(arr.map(el => el.id === id ? ... : el)) |
| Delete | arr.splice(i, 1) |
setArr(arr.filter(el => el.id !== id)) |
| Modifying object properties | obj.name = 'xxx' |
setObj({ ...obj, name: 'xxx' }) |
Core principle: always replace the old array/object with a new one. The spread operator
...and the array methods you have learned (map, filter) are the best partners for immutable updates.
useMemo - derived computed values
useMemo is used to cache computation results. When dependencies have not changed, it skips recomputation, avoiding unnecessary performance overhead.
Example
import
{
useState
,
useMemo
}
from
'react'
function
ArticleFilter
(
)
{
const
[
articles
]
=
useState
(
[
{
id
:
1
,
title
:
'React Getting Started'
,
category
:
'React'
}
,
{
id
:
2
,
title
:
'Promise Explained in Detail'
,
category
:
'JavaScript'
}
,
{
id
:
3
,
title
:
'Grid layout'
,
category
:
'CSS'
}
,
{
id
:
4
,
title
:
'React Hooks'
,
category
:
'React'
}
]
)
const
[
activeCategory
,
setActiveCategory
]
=
useState
(
'All'
)
// useMemo caches the filter result, recomputing only when dependencies change
const
filteredArticles
=
useMemo
(
(
)
=>
{
console.
log
(
'Recomputing filter result'
)
// Verify the caching effect
if
(
activeCategory
===
'All'
)
return
articles
return
articles.
filter
(
a
=>
a.
category
===
activeCategory
)
}
,
[
articles
,
activeCategory
]
)
// Dependency array
// Use useMemo to compute statistics
const
totalCount
=
useMemo
(
(
)
=>
articles.
length
,
[
articles
]
)
const
filteredCount
=
useMemo
(
(
)
=>
filteredArticles.
length
,
[
filteredArticles
]
)
return
(
<div>
<p Total{totalCount}>posts, current
{
filteredCount
}
articles
p
<
button onClick
=
{
(
)
=>
setActiveCategory
(
'All'
)
}
All
button
<
button onClick
=
{
(
)
=>
setActiveCategory
(
'React'
)
}
React
button
<
button onClick
=
{
(
)
=>
setActiveCategory
(
'JavaScript'
)
}
JavaScript
button
<
button onClick
=
{
(
)
=>
setActiveCategory
(
'CSS'
)
}
CSS
button
{
filteredArticles.
map
(
a
=>
(
<
div key
=
{
a.
id
}
< h3 {a.
title
}
h3
< span {a.
category
}
span
div
)
)
}
div
)
}
The dependency array of useMemo(fn, deps) must be complete: all component-internal variables used in the function should be declared in the array. React decides whether to recompute via shallow comparison.
Hands-on: Add Category Filtering to the Blog
Example
// File path: src/App.jsx
import
{
useState
,
useMemo
}
from
'react'
import
'./App.css'
function
App
(
)
{
const
[
articles
]
=
useState
(
[
{
id
:
1
,
title
:
'Complete Guide to React Getting Started'
,
summary
:
'Learn React from Scratch'
,
category
:
'React'
,
date
:
'2024-05-10'
}
,
{
id
:
2
,
title
:
'JS Asynchronous Programming Explained'
,
summary
:
'Understanding Promise and async/await'
,
category
:
'JavaScript'
,
date
:
'2024-05-08'
}
,
{
id
:
3
,
title
:
'CSS Grid Layout in Practice'
,
summary
:
'Responsive Layout with Grid'
,
category
:
'CSS'
,
date
:
'2024-05-05'
}
,
{
id
:
4
,
title
:
'React Hooks in Depth'
,
summary
:
'Deep Understanding of useState and useEffect'
,
category
:
'React'
,
date
:
'2024-05-03'
}
,
{
id
:
5
,
title
:
'Complete Guide to Flexbox'
,
summary
:
'Learn Flexbox Layout in One Article'
,
category
:
'CSS'
,
date
:
'2024-05-01'
}
,
]
)
const
[
activeCategory
,
setActiveCategory
]
=
useState
(
'All'
)
// Extract all categories (deduplicated)
const
categories
=
useMemo
(
(
)
=>
{
const
cats
=
articles.
map
(
a
=>
a.
category
)
return
[
'All'
,
...
new
Set
(
cats
)
]
}
,
[
articles
]
)
// Filter posts by category
const
filteredArticles
=
useMemo
(
(
)
=>
{
if
(
activeCategory
===
'All'
)
return
articles
return
articles.
filter
(
a
=>
a.
category
===
activeCategory
)
}
,
[
articles
,
activeCategory
]
)
return
(
<
div className
=
"app"
<
header className
=
"navbar"
<
h1 className
=
"logo"
RUNOOB Blog
h1
< nav <a href
=
"/"
Home
a
<
a href
=
"#"
About
a
nav
header
<
main className
=
"container"
<
h2 className
=
"section-title"
Latest Articles
h2
{
/* Category filter button group */
}
<
div className
=
"category-bar"
{
categories.
map
(
cat
=>
(
<button key={cat}className={activeCategory===cat?'active'>:
''
}
onClick
=
{
(
)
=>
setActiveCategory
(
cat
)
}
{
cat
}
button
)
)
}
div
<
p className
=
"result-info"
Total
{
filteredArticles.
length
}
articles
p
{
filteredArticles.
length
===
0
?
(
<
p className
=
"empty-tip"
No articles in this category yet
p
)
:
(
<
div className
=
"article-grid"
{
filteredArticles.
map
(
article
=>
(
<
div key
=
{
article.
id
}
className
=
"article-card"
<
div className
=
"card-content"
<
span className
=
"card-category"
{
article.
category
}
span
< h3 {article.
title
}
h3
< p {article.
summary
}
p
<
span className
=
"card-date"
{
article.
date
}
span
div
div
)
)
}
div
)
}
main
<
footer className
=
"footer"
< p © 2024RUNOOB Blog.
Powered
by React.
p
footer
div
)
}
export
default
App
Example
/* File path: append category filter button styles to src/App.css */
.category-bar
{
display
:
flex
;
gap
:
10px
;
margin-bottom
:
16px
;
flex-wrap
:
wrap
;
}
.category-bar
button
{
padding
:
6px
16px
;
border
:
1px
solid
#ddd
;
border-radius
:
20px
;
background
:
#fff
;
cursor
:
pointer
;
font-size
:
14px
;
transition
:
all 0.2s
;
}
.category-bar
button
.active
{
background
:
#1976d2
;
color
:
#fff
;
border-color
:
#1976d2
;
}
.category-bar
button
:hover
{
border-color
:
#1976d2
;
}
.result-info
{
color
:
#999
;
font-size
:
14px
;
margin-bottom
:
16px
;
}
Chapter Summary
In this chapter you mastered three core concepts of React state management: useState for creating and updating state, the immutable update principle (spread operator + map/filter), and useMemo for caching derived computed values.
Through the category filter feature, you experienced React's data-driven pattern of "setState -> re-render -> new view".