Sub topic 3
Building UIs from components
This chapter assumes you know JavaScript functions, objects, arrays and ES modules, and basic HTML and CSS. You do not need a React project yet. The code here is meant to be read first and run later, once you have scaffolded an app in the chapters that follow.
What a component is
A component is a reusable piece of UI. In modern React, a component is a JavaScript function that returns a description of what should appear on screen. React calls the function, reads what it returns, and updates the page to match.
function Greeting() {
return <p>Hello, reader.</p>
}The part that looks like HTML is JSX. The next chapter covers it in detail. For now, treat it as the value the function returns.
Components matter for three reasons:
- Reuse. You write a button, a card or a header once and use it in many places.
- Isolation. Each component handles one concern, so you can read and change it without holding the whole page in your head.
- Composition. Small components combine into larger ones, and the larger ones combine into a whole app.
Components as a tree
An app is a tree of components. One root component, usually called App, contains other components, which contain others. The browser's DOM is also a tree, and React keeps the two in step.
The three ProductCard boxes are three uses of one function. Each use is called an instance, and each instance receives its own data and, later, its own state.
Rules for defining components
React depends on a few conventions. Breaking them causes confusing errors.
- Names start with a capital letter.
Counteris a component.counteris treated as a built-in HTML tag. - A component returns something React can render. That is usually JSX, but it can also be a string, a number, an array, or
nullto render nothing. - A component returns one root. If you need several siblings, wrap them in a parent element or in a fragment (
<>...</>). - Components are defined at the top level of a module. Do not declare a component inside another component's body. Each render would create a new function, and React would treat it as a different component and discard its state.
- Components are pure with respect to rendering. Given the same props and state, a component should return the same output. It should not change variables outside itself while it renders.
The fifth rule is the one that matters most as apps grow. Side effects such as fetching data or changing the page title belong in event handlers or effects, not in the render path.
Writing and using a component
Here is a component in its own file, followed by a parent that uses it. These match the examples used later when you scaffold the project.
import { useState } from 'react'
function Counter({ label }) {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
)
}
export default Counterimport Counter from './Counter.jsx'
function App() {
return (
<main>
<h1>My first React app</h1>
<Counter label="Clicks" />
</main>
)
}
export default AppThree things happen here:
Counteris a function exported from its module withexport default.Appimports it and uses it as a tag,<Counter label="Clicks" />.Apppasseslabelas an attribute.Counterreceives it as a property of its argument. Props and state are covered in their own chapters.
Using the tag does not call Counter yourself. React calls it when it needs the output, which may happen many times.
Instances are independent
Each time you write a component tag, React creates a separate instance with its own state. Add two counters:
import Counter from './Counter.jsx'
function App() {
return (
<main>
<Counter label="Apples" />
<Counter label="Oranges" />
</main>
)
}
export default AppClicking the Apples button does not change the Oranges count. The function code is shared, but the remembered values are not. This is why a component works as a template and not as a singleton.
Composing larger components
A component can use any other component, including ones in other files. Splitting happens naturally when a piece of UI is repeated, or when a component becomes hard to read.
function ProductCard({ name, price }) {
return (
<li>
<strong>{name}</strong> costs ${price}
</li>
)
}
function ProductList({ products }) {
return (
<ul>
{products.map((product) => (
<ProductCard key={product.id} name={product.name} price={product.price} />
))}
</ul>
)
}
export default function App() {
const products = [
{ id: 1, name: 'Notebook', price: 4 },
{ id: 2, name: 'Pen', price: 2 },
{ id: 3, name: 'Stapler', price: 9 },
]
return <ProductList products={products} />
}The key prop on each ProductCard lets React match list items between renders. Use a stable identifier from your data, such as an id. Array indexes cause bugs when items are reordered or removed.
Where to split
Splitting too early and too late both cause trouble. These questions help:
| Question | If yes |
|---|---|
| Is the same markup used in more than one place? | Extract a component. |
| Does one piece have its own state or behavior? | Give it its own component. |
| Is the function longer than you can read in one screen? | Look for a natural boundary. |
| Would the component need many unrelated props? | The split may be in the wrong place. |
A common file layout is one component per file, with the file named after the component. Small helper components used by only one parent can stay in the same file.
Common errors
- Lowercase component name.
<counter />renders an unknown HTML element, not your component. You will see no output and possibly a console warning. - Forgetting to import. A missing import produces
Counter is not defined. - Mixing default and named exports. If the file uses
export default Counter, import it asimport Counter from .... If it usesexport { Counter }, import it asimport { Counter } from .... - Calling a component like a function. Write
<Counter />, notCounter(). A direct call skips React's bookkeeping, and hooks inside will break the rules of hooks. - Nesting component definitions. State resets on every parent render, as described in rule 4.
- Missing
keyin lists. React logs a warning, and updates can misbehave.
Summary of the model
A component is a function from inputs to a description of UI. An app is a tree of those functions. React calls them, compares what they return with the previous result, and updates only the parts of the page that changed. Your job is to write the functions. React's job is to keep the page in sync.
Exercise
In the following code, the Counter inside Parent loses its count whenever Parent re-renders. Explain why, and how to fix it. function Parent() { function Counter() { const [count, setCount] = useState(0) return <button onClick={() => setCount(count + 1)}>{count}</button> } return <Counter /> }
Show answer
Counter is declared inside Parent, so every render of Parent creates a new Counter function. React sees a different component type, unmounts the old instance and mounts a new one, which resets the state to 0. Move Counter to the top level of the module, outside Parent, and render it with <Counter /> from there.
Exercise
You render <Counter label="Apples" /> and <Counter label="Oranges" /> side by side. You click Apples three times. What do the two buttons show, and why?
Show answer
Apples shows 3 and Oranges shows 0. Each tag creates a separate instance of Counter, and each instance keeps its own state. The function code is shared, but the state values are not.
Exercise
Why does <counter label="Clicks" /> fail to render your Counter component, and what is the fix?
Show answer
React treats tags that start with a lowercase letter as built-in HTML elements, so it looks for an HTML element named counter. Component names must start with a capital letter. Rename the function and the tag to Counter.