Your first components

React · Essentials · 10 min

Components are the unit of everything in React; splitting UI into small components is the main design skill.

A component is a JavaScript function whose name starts with a capital letter and which returns markup (JSX). You use it like an HTML tag:

function Avatar() {
  return <img src="/ada.png" alt="Ada Lovelace" />;
}

Then <Avatar /> anywhere renders that image. Components can render other components, so an app is a tree: App renders Header, Feed and Sidebar, Feed renders many Posts, and so on.

The rules:

  • Capitalise names. <avatar /> is treated as an HTML tag; <Avatar /> calls your function.
  • Return one root. Wrap siblings in a <div> or a Fragment <>...</>, which adds no DOM node.
  • Define components at the top level of a module, never inside another component. A component defined inside another is a new function on every render, so React throws away its state and DOM each time.
  • Export them to use them from other files: export default function Profile() or a named export function Avatar().

Keep components small and focused. A good rule of thumb: if a piece of UI is reused, or a component's JSX no longer fits on a screen, extract a component. Component boundaries also become state and performance boundaries later, so they are worth getting right.

Example

// Profile.jsx
export function Avatar() {
  return <img className="avatar" src="https://i.imgur.com/MK3eW3As.jpg" alt="Katherine Johnson" />;
}

export default function Profile() {
  return (
    <>
      <h2>Katherine Johnson</h2>
      <Avatar />
      <Avatar />
    </>
  );
}

// App.jsx
import Profile from "./Profile.jsx";

export default function App() {
  return (
    <main>
      <Profile />
    </main>
  );
}

Remember

  • A component is a capitalised function that returns JSX
  • Use <>...</> (Fragment) to return several elements without an extra DOM node
  • Declare components at module top level and import/export them like any module

Watch out for

  • Defining a component inside another component, which resets its state on every render.

Check yourself

  1. Why should you not declare function Item() inside the body of function List()?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: react.dev/learn/your-first-component