React Basics: Build Interactive Interfaces
Lists and Effects
In this lesson you will
- Render a list with map and keys
- Show content conditionally
- Use useEffect for work outside rendering
Introduction
Real apps show lists of things: messages, products, tasks. They also show different things depending on the situation, and sometimes need to do work such as fetching data. This lesson covers all three.
Rendering lists
Use the array map method to turn each item into JSX:
React (JSX)
const fruits = ["Apple", "Banana", "Cherry"];
function FruitList() {
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}Each item needs a key, a unique and stable value, usually an id from your data. React uses keys to track which item is which when the list changes. Avoid using the array position as a key if items can be added, removed or reordered.
Quick quiz
Why does each item in a rendered list need a key?
Showing things conditionally
Because JSX is JavaScript, you can use normal conditions:
React (JSX)
function Status({ loggedIn }) {
if (!loggedIn) return <p>Please sign in.</p>;
return <p>Welcome back!</p>;
}
function Inbox({ unread }) {
return <h2>Inbox {unread > 0 && <span>({unread} new)</span>}</h2>;
}condition && something shows the something only when the condition is true. You can also use condition ? a : b.
Effects
Rendering should only work out what to show. Other jobs, such as fetching data, setting a timer or updating the page title, happen in an effect:
React (JSX)
import { useEffect, useState } from "react";
function Clock() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(id); // clean up when the component goes away
}, []);
return <p>{seconds} seconds since this appeared</p>;
}The second argument, [], is the dependency list. An empty list means "run once, after the first render". If you list values, the effect runs again when those values change. The function you return cleans up, so timers do not pile up.
Many things do not need an effect. If you can calculate something from props or state while rendering, just do that.
Where to go next
You now know the core ideas: components, props, state, lists and effects. Next steps are to build a small project, such as a to-do list, then learn about forms, routing and a framework such as Next.js, which this website itself uses.
Try it yourself
Make a to-do list: keep an array of tasks in state, show them with map and keys, and add a button that adds a new task.
Summary
- Render lists with
map, and give every item a stable key. - Use normal JavaScript conditions such as
&&and the conditional operator to show content. useEffectruns side effects after rendering, with a dependency list and cleanup.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading