Sub topic 1
What React is and what it is for
React is a JavaScript library for building user interfaces. You describe what the screen should look like for a given set of data, and React updates the browser to match. This chapter covers the working model of React, what problems it solves, where it stops, and the errors people commonly make when they first use it.
Prerequisites
This chapter assumes you already have:
- Basic HTML and CSS: elements, attributes, classes, and how the browser renders a page.
- JavaScript fundamentals: functions, objects, arrays, destructuring, arrow functions, and ES modules (
importandexport). - Some familiarity with the DOM (Document Object Model), the browser's tree of page elements, and with methods such as
document.getElementById. - A terminal and a working Node.js and npm install. You will need them in later chapters, not in this one.
The problem React addresses
A web page is a tree of elements called the DOM. A small page can be updated by hand with code like this:
const button = document.getElementById('like')
let likes = 0
button.addEventListener('click', () => {
likes += 1
button.textContent = `Likes: ${likes}`
})This is imperative code. You tell the browser each step: find the element, change its text, and repeat when something happens. It works until the page grows. When many pieces of data appear in many places, you must remember every spot that depends on each value and update all of them in the right order. If you miss one, the screen shows stale or contradictory data.
React takes a different approach. You write code that says what the UI should be for the current data. React works out which DOM changes are needed.
Declarative UI: the screen as a function of state
State is data that changes over time and affects what the user sees, such as a counter value, the text in a form field, or a list of loaded items. React's central idea is that the UI is a function of that state:
UI = f(state)You do not write "when the user clicks, change this text". You write "given a count, show a button with that count". When the count changes, React calls your code again, compares the new result with the previous one, and applies only the differences to the DOM.
This process has three phases:
- Trigger. Something causes a render: the first load, or a state change.
- Render. React calls your component functions to compute a description of the UI. Nothing in the browser changes yet.
- Commit. React compares the new description with the previous one and applies the minimal set of DOM changes.
The description React builds in the render phase is a tree of plain JavaScript objects, often called the virtual DOM. Comparing two such trees is cheap, so React can find the smallest set of real DOM changes. You rarely need to think about this, but it explains why your component code must be free of side effects: React may call it more than once.
Components
A component is a reusable piece of UI. In modern React, a component is a JavaScript function that returns a description of what to show. Component names start with a capital letter, which is how React tells them apart from ordinary HTML tags.
function Greeting() {
return <h1>Hello, React</h1>
}Components can contain other components, so an application becomes a tree. A page might hold a Header, a ProductList, and a Footer. ProductList in turn holds many ProductCard components. Each one can be written, tested, and reasoned about on its own.
JSX
The markup-like syntax inside return is JSX. It is not HTML and it is not a string. It is syntax that a build tool converts into JavaScript function calls that create the objects described above. This is one reason React projects need a build tool, which later chapters cover.
JSX differs from HTML in a few ways that cause many early errors:
| HTML | JSX | Reason |
|---|---|---|
| `class="card"` | `className="card"` | `class` is a reserved word in JavaScript |
| `for="email"` | `htmlFor="email"` | `for` is a reserved word |
| `<br>` | `<br />` | Every tag must be closed |
| `onclick="run()"` | `onClick={run}` | Handlers are camelCase and receive a function |
| `style="color: red"` | `style={{ color: 'red' }}` | `style` takes an object |
Curly braces switch from markup back to JavaScript. Any expression can go inside them:
function Price({ amount }) {
return <p>Total: {(amount * 1.2).toFixed(2)}</p>
}A component must return a single root. To return siblings without an extra wrapper element, use a fragment, written <>...</>.
Props
Props (short for properties) are the inputs to a component. A parent passes them as attributes, and the child receives them as one object, usually destructured in the parameter list.
function Badge({ text, color = 'gray' }) {
return <span style={{ background: color }}>{text}</span>
}
function Example() {
return <Badge text="New" color="green" />
}Props are read-only. A component must never change the props it receives. If a value needs to change, it belongs in state, owned by the component or by a parent that passes both the value and a function to change it.
State and the useState hook
A hook is a function whose name starts with use and that lets a component use a React feature. useState gives a component a value that React remembers between renders.
import { useState } from 'react'
function LikeButton() {
const [likes, setLikes] = useState(0)
return (
<button onClick={() => setLikes(likes + 1)}>
Likes: {likes}
</button>
)
}
export default LikeButtonuseState(0) returns a pair: the current value and a setter function. Calling the setter schedules a new render with the new value. Compare this with the imperative example earlier. There is no code that finds the button or edits its text. The text comes from likes, and changing likes is the only step.
Common errors
- Changing state directly. Writing
likes = likes + 1oritems.push(x)does not trigger a render. Always call the setter, and give it a new array or object instead of mutating the old one. - Expecting state to update immediately. After
setLikes(likes + 1), the variablelikesin the current call still holds the old value. The new value appears in the next render. When the next value depends on the previous one, pass a function:setLikes(n => n + 1). - Lowercase component names.
<badge />is treated as an HTML tag, not yourBadgecomponent. - Calling a component like a function. Write
<Badge />, notBadge(). React must manage the call so that hooks work. - Calling hooks conditionally. Hooks must run in the same order on every render. Do not put them inside
ifstatements, loops, or after an earlyreturn. - Calling the handler instead of passing it.
onClick={setLikes(1)}runs during render and causes an infinite loop. UseonClick={() => setLikes(1)}. - Missing keys in lists. When rendering an array, give each element a stable
keyso React can match items between renders.
What React is not
React handles the view layer only. It does not include routing, data fetching, or a build system. You pick those separately or use a framework built on React. React also does not require a single-page app: it can render one widget on an existing page or a whole application.
What React is a good fit for
React works well when:
- the interface has many pieces of changing data;
- the same UI pieces appear in several places;
- several people work on one interface and need clear boundaries between parts.
It adds little for a mostly static page with a few small interactions, where plain HTML and a small script are simpler.
Exercise
A component contains const [count, setCount] = useState(0) and a click handler that runs setCount(count + 1); setCount(count + 1). After one click, what does count become, and why? How would you make it increase by 2?
Show answer
It becomes 1. Both calls read the same count value (0) from the current render, so each one asks for 1. To add 2, use the updater form: setCount(n => n + 1); setCount(n => n + 1). React applies each function to the latest queued value.
Exercise
Why does class="card" fail to work as expected in JSX, and what do you write instead?
Show answer
JSX attributes map to JavaScript property names, and class is a reserved word in JavaScript. Write className="card".