Hello! Welcome to your next lesson on handling side effects in React.
In our previous lesson, we established a crucial principle: React's rendering process must be pure. Side effects—any interaction with the world outside a component's scope—must be handled separately to avoid unpredictable behavior and performance problems. We identified the useEffect hook as React's dedicated tool for this job, allowing us to run code after the render and commit phases are complete.
Today, we move from the why to the how. This lesson will teach you the syntax of the useEffect hook and how to use it to perform one of the most common side effects: fetching initial data when a component first appears on the screen.
1. The Anatomy of the useEffect Hook
The useEffect hook is a function you call inside your functional component. It accepts two arguments:
- A function that contains your side effect logic.
- An optional dependency array that controls when the effect function is executed.
Let's start with the first argument.
import React, { useEffect } from 'react';
function MyComponent() {
// The function passed to useEffect is the "effect" itself.
useEffect(() => {
// This code is your side effect.
// It will run AFTER the component renders.
console.log('Component has rendered!');
});
return <div>My Component</div>;
}
The function you pass to useEffect is where you'll put your API calls, DOM manipulations, or any other side effect. React guarantees that it will run this function only after it has finished rendering the component and updating the DOM.
2. Controlling When Effects Run: The Dependency Array
By default, if you don't provide the second argument (the dependency array), the effect function will run after every single render of the component. This is rarely what you want. Imagine an effect that fetches data; you don't want to re-fetch that data every time a minor piece of state changes in the component.
This is where the second argument, the dependency array, comes in. It lets you specify which values the effect "depends on" and tells React to only re-run the effect if one of those values has changed.
Let's explore the two most fundamental ways to use this array.
React Component Lifecycle: A Deep Dive for Beginners
This article, 'React Component Lifecycle: A Deep Dive for Beginners', which we touched on in the last lesson, has a very clear summary of how the dependency array works. It will help you visualize the different behaviors.
Please read the section titled 'When is useEffect called?'. Pay close attention to the three code examples that show useEffect with no dependency array, with an empty array [], and with a variable in the array.
Based on that reading, let's solidify the two main patterns we're focusing on today:
-
Running After Every Render (Generally Avoid)
useEffect(() => { // Runs after the initial render AND every subsequent re-render. });This is the default behavior when you omit the dependency array. It's useful in some specific cases, but most of the time it leads to performance issues or infinite loops.
-
Running Only Once on Mount
useEffect(() => { // Runs only once, after the component's initial render. }, []); // An empty dependency array.Providing an empty array
[]tells React that your effect doesn't depend on any props or state from your component. Therefore, it only needs to run the effect once when the component is first added to the DOM (when it "mounts") and never again. This is the perfect pattern for setup logic, like fetching initial data.
We will explore the third pattern—providing variables in the dependency array—in detail in our next lesson. For now, mastering the "run once" pattern is our main goal.
3. Practical Application: Fetching Data with useEffect
Let's build a component that fetches data from an API and displays it. This is the canonical example for useEffect and combines what you've learned about useState with your new knowledge of side effects.
Our goal is to create a component that:
- Renders a "Loading..." message initially.
- When it mounts, triggers an API call to fetch data.
- Once the data arrives, updates its state and re-renders to display the data.
The following video provides an excellent step-by-step guide to implementing this pattern.
React Typescript 2023 - 17. useEffect
The video 'React Typescript 2023 - 17. useEffect' by Teddy Smith demonstrates exactly how to fetch data within a useEffect hook. It covers setting up state, defining the async fetch function inside the effect, and updating the state.
Watch from 07:09 to 10:03. Notice how he uses useState to store the fetched data, useEffect with an empty array [] to trigger the fetch, and an async function inside the effect to handle the asynchronous API call.
Let's recap the key steps from the video with a slightly different example. Imagine we want to fetch a user's profile from an API.
Step 1: Define the state and data types
First, we need a place to store our data. We'll use useState and initialize it to null, since we don't have any data at the start. Your TypeScript skills are valuable here for defining the shape of our data.
import React, { useState, useEffect } from 'react';
// Define the type for our user data
interface UserProfile {
id: number;
name: string;
email: string;
}
function UserProfileComponent() {
const [user, setUser] = useState<UserProfile | null>(null);
// ... rest of the component
}
Step 2: Create the useEffect hook
We want to fetch data only once, so we'll use useEffect with an empty dependency array [].
// Inside UserProfileComponent
useEffect(() => {
// Our data fetching logic will go here.
}, []); // Empty array means this runs only once on mount.
Step 3: Implement the data fetching logic
The function passed to useEffect cannot be async directly. This is because useEffect can optionally return a cleanup function (which we'll cover in a future lesson), and an async function implicitly returns a Promise, not a potential cleanup function.
The standard pattern is to define an async function inside the effect and then call it immediately.
// Inside UserProfileComponent
useEffect(() => {
const fetchUser = async () => {
try {
const response = await fetch('https://api.example.com/user/1');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data: UserProfile = await response.json();
setUser(data); // Update state with the fetched data
} catch (error) {
console.error("Failed to fetch user:", error);
// In a real app, you'd also set an error state here
}
};
fetchUser(); // Call the async function
}, []); // Runs once
Step 4: Add conditional rendering
Since our user state starts as null, our component needs to handle this initial state. We can show a loading message while the data is being fetched.
// Inside UserProfileComponent
if (!user) {
return <div>Loading profile...</div>;
}
return (
<div>
<h1>{user.name}</h1>
<p>Email: {user.email}</p>
</div>
);
By combining these steps, you have a component that correctly separates its rendering logic from the side effect of fetching data, ensuring a predictable and efficient behavior.
Test your understanding!
A developer wrote a component to update the browser tab's title.
// INCORRECT CODE
import React, { useState } from 'react';
function DocumentTitleUpdater() {
const [count, setCount] = useState(0);
// Side effect directly in the render body
document.title = `You clicked ${count} times`;
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
This code "works," but it violates the principles we've learned. How would you refactor this component to correctly handle the document.title side effect using useEffect? When should this effect run?
Show answer
The side effect of updating document.title should be moved into a useEffect hook. This effect depends on the count state variable, so count should be included in the dependency array. This ensures the title is updated only when the count actually changes, not on every re-render for other reasons.
Here is the corrected code:
// CORRECT CODE
import React, { useState, useEffect } from 'react';
function DocumentTitleUpdater() {
const [count, setCount] = useState(0);
// Correctly handle the side effect with useEffect
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // The effect now "depends on" count
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Note: This example gives a sneak peek into the next lesson's topic—using non-empty dependency arrays. The key takeaway is moving the side effect out of the render body.
Conclusion
You've now learned the fundamental mechanics of useEffect. You can confidently write components that perform initial setup tasks or fetch data without polluting the render phase.
Key Takeaways:
useEffect(effectFunction, dependencyArray)is the hook for managing side effects.- The
effectFunctioncontains your side effect logic and runs after rendering. - The
dependencyArraycontrols when the effect runs. - An empty dependency array
[]is a powerful tool to make an effect run only once when the component mounts. - The standard pattern for
asyncoperations inuseEffectis to define and call anasyncfunction from within the effect.
Next Steps
So far, we've used useEffect to run code once on mount. But what if we want an effect to re-run whenever a prop or state value changes? That's the real power of the dependency array. In the next lesson, we will control the execution of effects using the dependency array, enabling our components to react and synchronize with changes in your application's data flow.