Components and JSX

Compose components

Build a larger interface by nesting small components and keeping each one responsible for a coherent piece of UI.

Components become useful when they compose into a larger interface.

function Article() {
  return (
    <article>
      <h2>Forms are an HTTP interface</h2>
      <p>The browser sends named values to a URL.</p>
    </article>
  )
}

function Page() {
  return (
    <>
      <Header />
      <main>
        <Article />
      </main>
    </>
  )
}

Page controls the page structure. Article controls one content item. Header can be reused across pages.

Composition keeps data flow visible. A parent can pass data down through props and receive events through callback props. The child does not need to know the whole application.

Split a component when a piece has a clear responsibility, repeats, owns state, or is easier to test on its own. Keep one-off markup together when another file and prop interface would add more ceremony than clarity.

Do not call a component as Article(). Use <Article /> so React can track its position, Hooks, and state as part of the tree.

Move the article text into props next. If the prop list becomes awkward, reconsider where the component boundary belongs.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →