Hey everyone! π
So you've started your React journey. You've probably made a component, maybe used useState
to make a counter click. That's a huge step! But soon you hit a wall: "How do I show a list of things? And how do I make my app do something automatically when it loads?"
If you've asked these questions, you're in the right place. Today, we're going to unlock the next level of React by learning its dynamic duo:
-
.map()
: The tool for turning a list of data into a list of UI elements. -
useEffect()
: The hook for running code after your component appears on the screen.
Master these two, and you can build almost anything. Let's dive in!
Part 1: From Plain Data to a Beautiful List with .map()
Imagine you have a list of tasks for a to-do app. In JavaScript, that's just an array of objects:
const tasks = [
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build a project' },
{ id: 3, text: 'Get some sleep' }
];
How do we display this on our page? A beginner might be tempted to do this:
// β The hardcoded, inflexible way
function TodoList() {
return (
<ul>
<li>Learn React</li>
<li>Build a project</li>
<li>Get some sleep</li>
</ul>
);
}
This works, but it's not dynamic. If we add a new task to our tasks
array, our UI won't update. We want our UI to be a direct reflection of our data.
Enter .map()
.map()
is a standard JavaScript function that acts like an assembly line for arrays. It takes an array in, does something to every single item, and pushes out a new array. We'll use it to turn our array of task data into an array of task list items.
Here's how we do it:
// src/components/TodoList.js
import React from 'react';
// Our data! In a real app, this might come from an API.
const tasks = [
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build a project' },
{ id: 3, text: 'Get some sleep' }
];
function TodoList() {
return (
<div>
<h2>My Tasks</h2>
<ul>
{/* We use {} to enter JavaScript mode */}
{tasks.map( (task) => {
// For each 'task' in the 'tasks' array, create this JSX:
return <li key={task.id}>{task.text}</li>
})}
</ul>
</div>
);
}
export default TodoList;
Let's break down the magic inside the <ul>
:
-
{ tasks.map(...) }
: We tell JSX, "Get ready for some JavaScript!" and we call the.map
function on ourtasks
array. -
(task) => { ... }
: This is our "assembly line instruction". For every item in the array, we'll temporarily call ittask
. -
return <li ... >
: This is what we create for each task. -
key={task.id}
: THIS IS SUPER IMPORTANT. React needs a uniquekey
for each item in a list to keep track of it efficiently when things change. Always use a unique identifier from your data, like anid
. -
{task.text}
: We access thetext
property of the currenttask
object to display it.
And just like that, you've created a dynamic list! If you add another object to the tasks
array, a new <li>
will automatically appear.
π§ Key Takeaway for .map()
: Use .map()
to transform an array of data into an array of JSX elements. Data in, UI out.
Part 2: The "After It Loads" Hook: useEffect
Okay, our list is great. But what if we want to do something after our component appears on the screen? For example, maybe we want to log a message to the console or change the page's title.
This is a "side effect"βan action that affects something outside of the component itself. For all side effects, we use the useEffect
hook.
Let's do something simple: we'll change the browser tab's title as soon as our TodoList
component loads.
Step 1: Import useEffect
Just like useState
, you have to import it from React.
import React, { useEffect } from 'react';
Step 2: Call useEffect
in Your Component
The useEffect
hook takes two arguments:
- A function: The code you want to run (the "effect").
- A dependency array: The rule for when to run it.
// src/components/TodoList.js
import React, { useEffect } from 'react';
// ... tasks array is still here ...
function TodoList() {
// π Our new useEffect hook!
useEffect(() => {
// This is the "effect" we want to run.
document.title = "You have 3 tasks to do!";
}, []); // <-- This is the dependency array.
return (
<div>
{/* ... our .map() from before is still here ... */}
</div>
);
}
Now, when your app loads, look at the browser tab. The title will change!
The Magic of the Dependency Array []
That []
at the end is the most crucial part of useEffect
. It tells React when to run your code.
[]
(Empty Array): This means "Run this effect only ONCE, right after the component first renders on the screen." This is perfect for things like fetching initial data, setting up timers, or what we just did. It's the "Grand Opening" effect.(No Array): If you leave off the array completely (
useEffect(() => { ... })
), the effect will run after every single render. This is usually a bug and can cause infinite loops! π¨[someVariable]
(Array with a variable): This tells React, "Run this effect once, and then run it again any timesomeVariable
changes." This is more advanced, but useful for reacting to changes in props or state.
π§ Key Takeaway for useEffect()
: Use useEffect(() => { ... }, [])
to run code once, right after your component mounts. Itβs your go-to for setup operations.
Your Journey From Here π
You've just learned two of the most powerful tools in your React toolkit.
- You can now display any list of data with
.map()
. - You can now run code on component load with
useEffect()
.
Can you see how they fit together? Imagine using useEffect
to fetch that tasks
array from a server on the internet, and then using .map
to display it. That's the foundation of almost every modern web application.
You've taken a huge step today. Keep building, keep experimenting, and happy coding!
Top comments (0)