Effects and data fetching
Synchronise with the outside world without leaking requests or state.
What you will be able to do
- Declare every reactive dependency in the dependency array.
- Use AbortController to cancel fetches when the effect is cleaned up.
- Do not use an effect for values you can compute during render.
In plain English
Effects run after render. An effect that fetches data needs a cleanup path and must ignore late responses after the component unmounts or dependencies change. Prefer a data library when the application grows.
import { useEffect, useState } from 'react'
export default function LessonLoader({ slug }) {
const [lesson, setLesson] = useState(null)
useEffect(() => {
const controller = new AbortController()
fetch('/api/lessons/' + slug, { signal: controller.signal })
.then((response) => response.json())
.then(setLesson)
.catch((error) => {
if (error.name !== 'AbortError') console.error(error)
})
return () => controller.abort()
}, [slug])
return lesson ? <h2>{lesson.title}</h2> : <p>Loading…</p>
}Your turn
MediumCancel a fetch
Add an AbortController to a fetch effect and abort the request in the cleanup function.
JSX · starter
useEffect(() => {
fetch('/api/lessons').then((r) => r.json())
}, [])Check your understanding before moving on.
Knowledge checkQuestion 1
What is the cleanup function for in an effect?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.