MENU
Getting Started with React
There are two ways into React. You can drop three lines into an HTML file and have a working component in a minute, which suits trying an idea or adding one interactive widget to a page that is otherwise server-rendered. Or you can scaffold a project with a build tool, which is what every real application uses: JSX compiled ahead of time, hot module replacement while you edit, and a minified bundle at the end.This section walks both paths, then explains the files a scaffolded project gives you, the frameworks that sit a level above, and the two tools you will keep open all chapter.2.1.1 What React Is and the Problem It Solves
React is an open-source (MIT) library for building user interfaces, created at Facebook and now developed by the React Foundation and a large community. It runs in the browser, on the server through Node.js, and â via React Native â on iOS and Android. It is not a framework: no router, no HTTP client, no opinion about folder layout.The problem it solves is the one Volume 1 leaves you with. Plain DOM code keeps the truth of your interface in the DOM itself, so every state change becomes a list of edits: find the counter, set its text, find the empty-cart message, hide it, enable the checkout button. Miss one edit and the screen disagrees with your data. React inverts that: you write a function returning what the screen should look like for the current data, and React works out the edits.
Figure 2.1: Imperative DOM updates versus React's
render-and-reconcile cycleA component is a function, and given the same props and state it must
return the same markup â that is what makes the comparison safe to run
whenever React likes. Its return value is neither DOM nor a string: it
is a tree of plain objects describing elements, cheap to build and cheap
to throw away. React keeps the previous tree, walks both, and produces
the shortest list of DOM operations that turns one into the other:
reconciliation.2.1.2 A Short History of React
React grew out of a Facebook prototype by Jordan Walke, first called F-Bolt and then FaxJS. It shipped to the News Feed in 2011 and to Instagram in 2012, and was open-sourced at JSConf US in Facebook's Seattle office on 29 MayThe reception was hostile: to an audience trained on templates and separation of concerns, mixing markup
2.1.3 Adding React Directly to an HTML Page
You can run React with no build step, which is the fastest way to try an idea or to add one interactive widget to a page your server already renders. Three things have to be in place: React and React DOM as modules, a DOM node to render into, and something that understands JSX.Older tutorials load react.development.js and react-dom.development.js as UMD scripts and use the globals React and ReactDOM. That recipe stops working at React 19, whose UMD builds were dropped: unpkg.com/react@19.3.0/umd/react.development.js returns 404. The replacement is an import map, which lets the browser resolve a bare specifier such as react to a URL, so the import statements of a real project also work in a single file.<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="importmap">
{"imports": {
"react": "https://esm.sh/react@19.3.0",
"react-dom/client": "https://esm.sh/react-dom@19.3.0/client"
}}
</script>
<script src="https://cdn.jsdelivr.net/npm/@babel/standalone@8.0.5/babel.min.js"></script>
<style>body { font: 16px system-ui, sans-serif; margin: 20px } button { font: inherit }</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel" data-type="module">
import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
function LikeButton() {
const [likes, setLikes] = useState(0);
return <p>
<button onClick={() => setLikes(likes + 1)}>Like</button>
{' '}{likes} {likes === 1 ? 'person likes' : 'people like'} this.
</p>;
}
createRoot(document.getElementById('root')).render(<LikeButton />);
</script>
</body>
</html>
Figure 2.2: Browser output of Listing 2.1Click the button and the sentence updates: setLikes schedules a
re-render, LikeButton runs again with the new value, and React rewrites
one text node. createRoot attaches React to a DOM container and is the
only entry point in React 19 â ReactDOM.render was removed.Two details are easy to miss. type="text/babel" hands the script to
Babel Standalone instead of the browser, and data-type="module" tells
Babel the code contains import statements, so it re-injects the compiled
result as a module. Babel Standalone compiles JSX with the
classic runtime, turning <p> into
React.createElement('p', ...), so React must be imported by name; drop
that import and the page throws React is not defined. Build tools use
the automatic runtime and need no such import (Section 2.2.1).2.1.4 Creating a Project with Vite
For anything you intend to keep, start with a build tool. Vite is the lightest of the recommended options: it compiles JSX and TypeScript with Oxc, a transformer written in Rust, serves your source as native ES modules in development so startup does not depend on project size, and bundles for production with Rolldown.npm create vite@latest catalog -- --template react
cd catalog
npm install
npm run dev
VITE v8.3.0 ready in 277 ms
â Local: http://localhost:5177/
â Network: use --host to expose
vite v8.3.0 building client environment for production...
â 20 modules transformed.
dist/index.html 0.45 kB â gzip: 0.29 kB
dist/assets/index-DykytF2W.css 4.10 kB â gzip: 1.47 kB
dist/assets/index-CyBHeG3D.js 222.52 kB â gzip: 69.26 kB
â built in 302ms
2.1.5 The Anatomy of a React Project
A scaffolded project has fewer moving parts than it looks. Everything below src/ is yours; everything above it is configuration you will touch a few times a year.catalog/
ââ index.html the real entry point: loads /src/main.jsx as a module
ââ package.json dependencies and the dev / build / preview scripts
ââ vite.config.js Vite plugins; the React plugin enables JSX and HMR
ââ public/ copied to dist/ byte for byte, served as /favicon.svg
ââ src/
ââ main.jsx creates the React root and renders <App />
ââ App.jsx the root component; index.css and App.css sit beside it
ââ assets/ images imported from code, hashed at build time
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
)
2.1.6 Frameworks and Other Toolchains
Vite gives you a bundler and nothing else. The moment an application needs routes, data loading or server rendering, you either assemble those yourself or start from a framework that already made the decisions. The React documentation now recommends the second path for most new applications.2.1.7 Online Editors and Sandboxes
Nothing in this chapter needs a local install to try. A browser sandbox gives you a React project in seconds and â more usefully â a URL. When you report a bug or share a snippet with a colleague, a link to a running reproduction saves everyone the "it works here" round trip; maintainers of React libraries routinely close issues that arrive without one.2.1.8 React Developer Tools
The Elements panel shows the DOM React produced, which is the wrong level of detail: it cannot say which component rendered a node, what props it received or what its state is. React Developer Tools, the official extension, adds two tabs â Components and Profiler â that work at the level you write in. Install it from the Chrome Web Store, Firefox Add-ons or the Edge add-ons site; for React Native and other non-browser targets, npx react-devtools opens the same interface as a standalone app.
Figure 2.3: The Components tab of React Developer Tools (image:
react.dev, CC BY 4.0)Select a node in the component tree and the right-hand pane lists its
props, state and hooks in order, all editable: change a prop and the
component re-renders immediately, the fastest way to check an empty
state or an error branch without touching code. The eye icon reveals the
matching DOM node in the Elements panel, <> jumps to the source,
and the bug icon logs props and state to the console.The Profiler tab records a session and reports, per commit, which
components re-rendered and how long they took. Section 2.12.1 uses it
properly; for now, turn on Highlight updates when components
render in the settings gear and click around. Boxes flashing
around parts of the screen that did not change mean some state lives too
high in the tree.