Course outline · 0% complete

0/28 lessons0%

Course overview →

UI as a function of data

lesson 1-2 · ~10 min · 2/28

UI as a function of data

The core React equation is:

UI = f(data)

Given the same data, the same UI comes out. Change the data, run f again, get the new UI. We can feel this idea in plain JavaScript before touching React itself. Below, render is an ordinary function that takes a user object and returns a string of HTML. It never touches the DOM. It just answers the question: for this data, what should the screen say?

Code exercise · javascript

Run this. Notice that render is called twice with different data and produces different UI, with no manual patching in between.

What React adds on top

Our render returns a string, and replacing a whole page with a new string would be slow and would lose things like cursor position in an input. React does better:

  • Your components return a lightweight description of the UI (element objects, not strings).
  • React compares the new description with the previous one. This comparison is often called diffing.
  • React then applies only the minimal real DOM changes, for example updating one text node instead of rebuilding the page.

So the mental model stays UI = f(data), and React makes it fast. Everything in the rest of this course, components, props, state, effects, hangs off this one equation.

Code exercise · javascript

Your turn. Write renderBadge(product) that returns "<span>SALE: NAME</span>" when product.onSale is true, otherwise "<span>NAME</span>". The two console.log calls should print the expected output exactly.

Quiz

In the equation UI = f(data), what happens in React when the data changes?