Side Effects and Data Fetching - useEffect
In this chapter you will learn React's most important side-effect Hook - useEffect - and use fetch at the right time to load blog data from a JSON file.
What is a side effect?
In React, a side effect refers to operations unrelated to rendering:
- Requesting data from a server
- Manipulating localStorage
- Setting a timer with setInterval
- Manually modifying the DOM
- Subscribing to external events
Side effects cannot be executed directly inside a component's function body (that would run them on every render); they must be placed inside useEffect.
Basic usage of useEffect
Example
import
{
useState
,
useEffect
}
from
'react'
function
HomePage
(
)
{
const
[
message
,
setMessage
]
=
useState
(
'Loading...'
)
// useEffect(fn, deps): run side effects after the component renders
useEffect
(
(
)
=>
{
console.
log
(
'Component mounted to DOM, side effects can now run'
)
setMessage
(
'Data loaded!'
)
}
,
[
]
)
// Empty dependency array = run only once after the first render
return
<p{message}p}>The difference between omitting the dependency array and using an empty array:useEffect(fn) Runs after every render;useEffect(fn, []) Runs only once after the first render. The former easily causes infinite loops (setState in the effect -> triggers a render -> runs the effect again -> ...), and is almost never used.
Loading JSON Data with fetch
As with Vue3, we put the post data in public/posts.json file.
Step 1: Create the Data File
Example
// File path: public/posts.json
[
{
"id": 1,
"title": "Complete Guide to React",
"summary": "Learn React Hooks from scratch, covering core concepts such as useState and useEffect.",
"content": "
Why Learn React?
React is currently one of the most popular front-end frameworks...
","category": "React",
"date": "2024-05-10"
},
{
"id": 2,
"title": "JavaScript Asynchronous Programming Explained",
"summary": "Understand Promises, async/await, the event loop, and the microtask queue in one article.",
"content": "
What Is Asynchronous?
JS is single-threaded...
","category": "JavaScript",
"date": "2024-05-08"
},
{
"id": 3,
"title": "CSS Grid Layout in Practice",
"summary": "Easily implement complex responsive layouts with CSS Grid.",
"content": "
Getting Started with Grid
Grid is a two-dimensional layout system...
","category": "CSS",
"date": "2024-05-05"
}
]
Step 2: Load data in useEffect
Example
// File path: src/pages/HomePage.jsx
import
{
useState
,
useEffect
,
useMemo
}
from
'react'
import
BlogCard from
'../components/BlogCard'
import
CategoryFilter from
'../components/CategoryFilter'
function
HomePage
(
)
{
const
[
articles
,
setArticles
]
=
useState
(
[
]
)
// Post data
const
[
isLoading
,
setIsLoading
]
=
useState
(
true
)
// Loading state
const
[
error
,
setError
]
=
useState
(
null
)
// Error message
const
[
activeCategory
,
setActiveCategory
]
=
useState
(
'All'
)
// useEffect loads data: empty dependency array = run only once after the first render
useEffect
(
(
)
=>
{
let cancelled
=
false
// Flag to prevent setState after the component unmounts
async
function
fetchPosts
(
)
{
setIsLoading
(
true
)
setError
(
null
)
try
{
const
res
=
await fetch
(
'/posts.json'
)
if
(
!
res.
ok
)
throw
new
Error
(
`HTTP $
{
res.
status
}
`
)
const
data
=
await res.
json
(
)
if
(
!
cancelled
)
{
setArticles
(
data
)
}
}
catch
(
err
)
{
if
(
!
cancelled
)
{
setError
(
err.
message
)
}
}
finally
{
if
(
!
cancelled
)
{
setIsLoading
(
false
)
}
}
}
fetchPosts
(
)
// Cleanup function: set cancelled to true when the component unmounts
return
(
)
=>
{
cancelled
=
true
}
}
,
[
]
)
const
categories
=
useMemo
(
(
)
=>
{
return
[
'All'
,
...
new
Set
(
articles.
map
(
a
=>
a.
category
)
)
]
}
,
[
articles
]
)
const
filteredArticles
=
useMemo
(
(
)
=>
{
if
(
activeCategory
===
'All'
)
return
articles
return
articles.
filter
(
a
=>
a.
category
===
activeCategory
)
}
,
[
articles
,
activeCategory
]
)
return
(
<
div
<h2 className
=
"section-title"
Latest Articles
h2
{
/* Loading */
}
{
isLoading
&&
<
p className
=
"status-msg"
Loading, please wait...
p
}
{
/* Loading error */
}
{
error
&&
(
<
div className
=
"status-msg error"
<
p
Loading failed:
{
error
}
p
<
button onClick
=
{
(
)
=>
window.
location
.
reload
(
)
}
Retry
button
div
)
}
{
/* Data loaded */
}
{
!
isLoading
&&
!
error
&&
(
<>
<
CategoryFilter
categories
=
{
categories
}
activeCategory
=
{
activeCategory
}
onCategoryChange
=
{
setActiveCategory
}
/>
<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
=>
(
<
BlogCard key
=
{
article.
id
}
{
...
article
}
/>
)
)
}
div
)
}
)
}
div
)
}
export
default
HomePage
cancelledThe flag is a common pattern in React. When fetch is still in progress, if the user leaves the page (the component unmounts), subsequent setState calls will produce an error warning. Setting it in the cleanup functioncancelled = truecan skip setState after unmounting.
Cleanup function (Cleanup)
The callback function of useEffect can return a function, called a cleanup function.
It runs at two times: when the component unmounts and before the next effect runs.
Example
useEffect
(
(
)
=>
{
// Side effect: subscribe to an event
const
handleScroll
=
(
)
=>
console.
log
(
'Scrolled'
)
window.
addEventListener
(
'scroll'
,
handleScroll
)
// Return the cleanup function
return
(
)
=>
{
// Automatically remove the event listener when the component unmounts to prevent memory leaks
window.
removeEventListener
(
'scroll'
,
handleScroll
)
}
}
,
[
]
)
useEffect
(
(
)
=>
{
// Side effect: set a timer
const
timer
=
setInterval
(
(
)
=>
{
console.
log
(
'Runs every second'
)
}
,
1000
)
return
(
)
=>
clearInterval
(
timer
)
// clear timer
}
,
[
]
)
| Side effect | Needs cleanup? | Cleanup method |
|---|---|---|
| fetch request | Is | Use a cancelled flag or AbortController |
| Event Listening | Is | removeEventListener |
| Timer | Is | clearInterval / clearTimeout |
| Restore after modifying the DOM | Is | Restore the original state in cleanup |
| localStorage writes | No | No cleanup needed |
Four states for handling asynchronous requests
Any data request should cover the following four UI states:
| State | Conditional | UI |
|---|---|---|
| Loading | isLoading === true | Loading animation, skeleton screen |
| Success | Data returned | Render content normally |
| Failure | error !== null | Error message + retry button |
| Empty data | Data is an empty array | Empty state message |
Comparison with the Vue3 lifecycle
| Vue3 | React | Description |
|---|---|---|
onMounted |
useEffect(fn, []) |
Run after the first render |
watch(keyword, fn) |
useEffect(fn, [keyword]) |
Respond to specific data changes |
onBeforeUnmount |
useEffect 的 cleanup |
Clean up before the component is destroyed |
| No direct counterpart | useEffect(() => { fn; return cleanup }, [dep]) |
When dep changes, cleanup runs before fn |
Chapter Summary
In this chapter you mastered the core usage of useEffect: the three ways to write the dependency array, loading data asynchronously with fetch, handling four UI states, and the role of the cleanup function.
Now the blog data is loaded dynamically from an external JSON file, no longer hardcoded in JS.