Components
The unit React is built from: a function that returns markup, composed into a tree.
Writing a component
A component is a JavaScript function whose name starts with a capital letter and which returns JSX.
function WelcomeBanner() {
return (
<section className="banner">
<h1>Welcome</h1>
<p>Glad you are here.</p>
</section>
);
}
export default WelcomeBanner;You then use it like a tag:
import WelcomeBanner from "./WelcomeBanner.jsx";
function App() {
return (
<main>
<WelcomeBanner />
</main>
);
}The capital letter is load-bearing.
Composition
Components nest inside one another, and that nesting is how a real interface is assembled. A page is a component made of section components, each made of smaller pieces.
function Avatar() {
return <img className="avatar" src="/ada.jpg" alt="Ada" />;
}
function UserCard() {
return (
<div className="card">
<Avatar />
<h2>Ada Lovelace</h2>
</div>
);
}
function UserList() {
return (
<div className="list">
<UserCard />
<UserCard />
</div>
);
}Each component can be reasoned about on its own. That is the practical payoff: you read one small function at a time instead of one large page.
Returning nothing
A component that returns null renders nothing. This is a normal, expected return value, not an error.
function Warning({ show }) {
if (!show) return null;
return <p className="warning">Check your input.</p>;
}Components must be pure
Given the same inputs, a component should return the same output and should not change anything outside itself while rendering. React may call your function more than once before showing the result, and in Strict Mode it deliberately does.
let counter = 0;
// Wrong: modifies a value outside during render
function Bad() {
counter = counter + 1;
return <p>{counter}</p>;
}
// Right: derives output from its input
function Good({ counter }) {
return <p>{counter}</p>;
}Side effects — network requests, timers, writing to the document title — belong in event handlers or in useEffect, covered in chapter 12.
Class components
Before hooks arrived in React 16.8, stateful components were written as classes. You will still find them in older code.
class WelcomeBanner extends React.Component {
render() {
return <h1>Welcome</h1>;
}
}They are still supported and are not deprecated, but new code is written with functions. This guide uses functions throughout.
Where to draw the line
There is no rule about component size, but two signals are reliable. Split a component when a piece of it is used in more than one place, and when a piece has its own state that nothing else cares about. Splitting purely because a file feels long tends to produce indirection without benefit.