Welcome back, Code Warriors! ⚔️
In the previous episode (aka the Basic article), we played with LEGOs (Components), passed notes (Props), and managed our mood (State). If you missed it, go check it out first. I’ll wait.
Done? Cool. Now, let’s level up. 🚀
Today we’re tackling the Intermediate stuff. Sounds scary? Nah. We’re keeping it casual. We’re going to talk about:
- Hooks (specifically
useEffect) - The magic spell for side effects. - API Fetching - Getting data from the internet (because static sites are boring).
- Routing - Moving between pages without refreshing (magic!).
Grab your coffee. Let’s do this. ☕
1. useEffect: The After-Party Cleanup
We know useState is for memory. But what if you want to do something outside the component rendering? Like changing the document title, setting a timer, or fetching data?
That’s a “Side Effect”. And in React, we handle it with useEffect.
Think of useEffect like ordering food.
You call the restaurant (trigger effect), wait for the food (async operation), and maybe pay/tip when it arrives (cleanup).
import { useState, useEffect } from "react";
const Timer = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
// This runs AFTER the component renders
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);
// This is the "Cleanup" function (optional)
// It runs when the component disappears (unmounts)
return () => clearInterval(interval);
}, []); // <--- The dependency array (we'll explain this)
return <p>Timer: {seconds}</p>;
};
The Dependency Array [] is crucial:
[](Empty): Runs ONLY ONCE when the component is born (mount). Like “Hello World”.[count]: Runs every timecountchanges. Like a stalker watchingcount.- No array: Runs EVERY render. Chaos. Don’t do this unless you know what you’re doing.
2. API Fetching: Asking the Internet for Stuff
Most apps need real data. Weather, movies, crypto prices…
In React, we usually fetch data inside useEffect (because it’s a side effect!).
Imagine you’re at a restaurant.
- Mount: You sit down.
- Effect: You call the waiter (“Hey, give me the menu data”).
- State: While waiting, you show a “Loading…” spinner.
- Update: Food arrives -> You eat (Update State with data).
const UserList = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
// We can't make useEffect async directly, so we make a helper function
const fetchData = async () => {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
const data = await response.json();
setUsers(data); // Save the food
setLoading(false); // Stop the spinner
} catch (error) {
console.error("Chef burned the food!", error);
}
};
fetchData();
}, []); // Run once on mount
if (loading) return <p>Loading users...</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
See? Not rocket science. It’s just request -> wait -> update state.
3. Routing: The Teleporter
In the old days (MPA - Multi Page App), clicking a link meant the browser turned white, reloaded everything, and downloaded the CSS/JS again. Slow.
React apps are usually SPAs (Single Page Apps).
We use a Router (like react-router-dom) to “fake” navigation.
It looks like you changed pages, but actually, React just swapped the components instantly. Fast.
Think of it like a Teleporter vs Walking.
- Standard Link (
<a>): Walking out the door and entering another building. (Reload). - Router Link (
<Link>): Teleporting instantly to another room. (No Reload).
(Note: Since this blog is built with Astro, it handles routing differently, but in a pure React app like Create-React-App, you’d use this):
// Instead of <a href="/about">About</a>
import { Link } from "react-router-dom";
<Link to="/about">About Us</Link>;
And in your main file:
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
It just watches the URL and decides “Oh, URL is /about? I’ll show the <About /> component.”
Wrapping Up
We covered a lot!
- useEffect: For handling side effects and lifecycle.
- Fetching: Getting data from APIs inside useEffect.
- Routing: Swapping components to look like page navigation.
You’re no longer a beginner. You’re… an Intermediate React Developer. 🎉
Next up: Advanced Topics. We’ll talk about Performance (so your app doesn’t lag like a potato), Context (global state), and Custom Hooks.
Keep coding, stay hydrated! 💧