Sub topic 1
Components are functions that return UI
Prerequisites
This chapter assumes you already know:
- Modern JavaScript: functions, arrow functions, destructuring, and array
mapandfilter. - Basic HTML elements and attributes.
- ES modules, meaning
importandexport.
You do not need to know any React yet. Later chapters cover JSX syntax rules, props, state, and the other topics this chapter mentions.
What a component is
A React component is a JavaScript function that returns a description of part of a user interface. React calls the function, reads what it returns, and updates the page to match.
A component is not an HTML template and not a DOM element. It is a function, so it takes input, runs code, and produces output. The input is an object called props. The output is a tree of React elements, which you usually write with JSX.
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default function App() {
return <Greeting name="Ada" />;
}This file defines two components, Greeting and App. App is the default export, and it is the one a project's entry file typically renders. App returns <Greeting name="Ada" />, which asks React to call Greeting with the object { name: "Ada" }. Greeting destructures name in its parameter list and returns an <h1>.
The JSX in this example looks like HTML, but it is JavaScript syntax. A later chapter in this tutorial explains what it compiles to.
The rules that make a function a component
Three rules cover most of what you need.
- The name starts with a capital letter. React treats
<Greeting />as a component and<greeting />as a built-in HTML tag namedgreeting. A lowercase component name is one of the most common beginner errors, and it fails quietly: the browser gets an unknown element instead of your component. - It returns something React can render. That is usually JSX. It can also be a string, a number, an array, or
null. - You use it as a tag, not by calling it. Write
<Greeting name="Ada" />, notGreeting({ name: "Ada" }). React needs to call the function itself so it can track the component on the page.
The third rule matters more as you add features. A component that React manages can later remember values and respond to events. A function you call by hand cannot.
Returning nothing
A component can return null to render nothing. This is the normal way to hide a component.
function Banner({ message }) {
if (!message) {
return null;
}
return <p className="banner">{message}</p>;
}Returning undefined is a different case. In current React versions it is allowed, but in older ones it throws an error. A missing return is a frequent cause of this. Return null on purpose when you want an empty result.
Declarations, arrows, and exports
You can define a component with a function declaration or with an arrow function assigned to a constant. Both work the same way.
function Badge({ label }) {
return <span className="badge">{label}</span>;
}
const Tag = ({ label }) => <span className="tag">{label}</span>;
export { Badge, Tag };A function declaration is hoisted, so you can use it above where you define it in the file. A const arrow function is not, so it must be defined before the code that renders it runs.
Most codebases follow one convention per file:
- One main component per file, named after the file, as a default export.
- Small helper components in the same file, as named functions.
- Named exports when a file holds several related components.
When you import a default export, you pick the local name. Keep it capitalized and matching the component, or the code becomes hard to follow.
The single root requirement
A component returns one value. In JSX, that means one root element. This code is invalid:
function Broken() {
return (
<h1>Title</h1>
<p>Body</p>
);
}The cause is JavaScript, not React. A return statement returns one expression, and two adjacent JSX elements are two expressions. You can wrap them in a <div>, but that adds an extra element to the page. A fragment avoids that, and a later chapter covers it.
Parentheses after return also matter. If the JSX starts on the next line without them, JavaScript inserts a semicolon after return and the function returns undefined.
function Wrong() {
return
<p>This never renders.</p>;
}
function Right() {
return (
<p>This renders.</p>
);
}How React uses your function
Understanding the cycle helps you avoid several errors later.
The important points are:
- React calls your function, not you. You describe what the UI should look like for the current input.
- The function can run many times. React calls it again whenever its input changes or when something it depends on changes. Each call is called a render.
- Rendering is separate from updating the page. The function returns a description. React decides which parts of the real page to change.
Because a component can run many times, it should not do things like changing outside variables or writing to the page directly. The purity chapter explains this rule in full. For now, treat the function body as a calculation: given these props, return this UI.
Components calling components
Components are useful because they nest. A component can return other components as well as built-in HTML tags.
function Avatar({ name }) {
return <span className="avatar">{name[0]}</span>;
}
function UserRow({ name, role }) {
return (
<li>
<Avatar name={name} />
<strong>{name}</strong> ({role})
</li>
);
}
function Team() {
return (
<ul>
<UserRow name="Ada" role="Engineer" />
<UserRow name="Grace" role="Admin" />
</ul>
);
}Team renders two UserRow elements, and each UserRow renders an Avatar. The result is a tree of components that React expands into plain HTML elements.
Define each component at the top level of a module. Do not define a component inside another component's body.
function Parent() {
// Avoid: Child is a new function on every render of Parent.
function Child() {
return <p>Hi</p>;
}
return <Child />;
}Each time Parent runs, it creates a new Child function. React sees a different component type and throws away the old one, including anything it remembered, then builds a new one. This causes lost input text, lost focus, and wasted work. The fix is to move Child outside Parent and pass any data in through props.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Your component shows up as an empty or unknown element in the page | The name starts with a lowercase letter | Capitalize the name |
| "Adjacent JSX elements must be wrapped" | The component returns two sibling elements | Wrap them in one parent or a fragment |
| Nothing renders and no error appears | `return` is followed by a newline before the JSX | Put the JSX in parentheses starting on the `return` line |
| "Objects are not valid as a React child" | You put a plain object in the output | Render one of its fields instead |
| Component state resets on every update | The component is defined inside another component | Move it to the top level of the module |
| Component works once, then behaves oddly | You called `Comp()` instead of using `<Comp />` | Render it as a tag |
Calling a component as a function
It can seem harmless to call a component directly, because it is just a function:
function Label() {
return <b>Hi</b>;
}
function Page() {
return <div>{Label()}</div>;
}This works for a component this simple, so it can look fine in a quick test. The problem appears when Label later gains features React manages for a component, such as state. Calling it directly makes React treat its contents as part of Page. The rules for those features can then break in confusing ways. Use <Label /> from the start so the component stays independent.
Where components fit in a project
A typical project has a small entry file that renders one root component into a page element. Everything else is components imported from other modules.
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
const container = document.getElementById('root');
createRoot(container).render(<App />);createRoot comes from react-dom/client, which is the package that connects React to the browser DOM. The render call takes a React element. <App /> is that element, and from there React expands the whole tree.
Older tutorials may use ReactDOM.render. That API was replaced by createRoot in React 18, so prefer createRoot in new code.
Check your understanding
Exercise
A teammate writes function userCard() { return <p>Ada</p>; } and renders it with <userCard />. It does not show the component's output. What is wrong, and what is the fix?
Show answer
The name starts with a lowercase letter, so React treats userCard as a built-in HTML tag instead of a component. Rename the function to UserCard and render <UserCard />.
Exercise
This component renders nothing and gives no error. Why, and how do you fix it? function Note() { return <p>Remember this.</p>; }
Show answer
JavaScript inserts a semicolon after return because the JSX starts on the next line, so the function returns undefined. Put the JSX in parentheses that begin on the same line as return: return ( followed by the <p> element and );.
Exercise
A text input inside a component loses what the user typed every time the parent updates. The component is declared inside the parent's function body. Why does this happen, and what is the fix?
Show answer
Each render of the parent creates a new function, so React sees a different component type and discards the old instance along with its input state. Move the component to the top level of the module and pass any needed data through props.