Lesson 4 of 7 · 12 min · 2 hands-on steps
Thinking in React: UI = f(state)
The one idea behind React, Vue and every modern front-end framework.
The big idea
In the DOM lessons you updated the page by hand: find an element, change its text, add a class. In a big app, keeping hundreds of elements in sync with your data that way becomes a nightmare.
React flips it around:
The UI is a function of the state. Describe what the screen should look like for any data, and let the framework update the page.
function Greeting({ name, unread }) {
return `<h1>Hi ${name}!</h1>` + (unread > 0 ? `<p>You have ${unread} new messages</p>` : "");
}
console.log(Greeting({ name: "Ada", unread: 3 }));
console.log(Greeting({ name: "Ada", unread: 0 }));Same function, different data, different UI. That's all a component is.
What real React looks like
React uses JSX, HTML-like syntax inside JavaScript:
function ProductCard({ name, price, inStock }) {
return (
<div className="card">
<h3>{name}</h3>
<p>{inStock ? `$${price}` : "Sold out"}</p>
</div>
);
}
function ProductList({ products }) {
if (products.length === 0) return <p>No products yet</p>;
return products.map((p) => <ProductCard key={p.name} {...p} />);
}
Compare it to your string version in the practice below. It's the same thinking: props in, UI out, small components combined into bigger ones.
Why this matters
React is the most-requested front-end skill in junior job posts. Once "UI = f(state)" clicks, the syntax is the easy part. You'll set up a real React project on your own computer in the capstone.
🧪 Practice: 2 steps
0 / 2 doneStep 1 of 2 · A component is a function
In React, a component is a function that takes data (props) and returns UI. Practice the idea with strings.
Write ProductCard({ name, price, inStock }) that returns exactly:
<div class="card"><h3>Keyboard</h3><p>$49.99</p></div> when in stock, and the same but with <p>Sold out</p> instead of the price when inStock is false.
function ProductCard({ name, price, inStock }) {
return "";
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Components inside components
Write ProductList({ products }) that returns <section> + each product rendered with ProductCard + </section>. If there are no products, return <section><p>No products yet</p></section>.
function ProductCard({ name, price, inStock }) {
const detail = inStock ? `$${price}` : "Sold out";
return `<div class="card"><h3>${name}</h3><p>${detail}</p></div>`;
}
function ProductList({ products }) {
return "";
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
In React, what should you change to update what's on screen?
Create a free account to track your progress.