Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 132 ยท Components and Props

Designing Components

Learn how to split a UI into React components, design clean props APIs, decide when to extract, and build a filterable product table step by step using the thinking-in-React method.

Knowing the syntax of a component is easy. Knowing where to draw the boundaries is the real skill. Should this card be one component or three? Should the filter box own its text, or should its parent? Which props should a Button accept? Good answers make a codebase pleasant to change; bad answers produce components with fifteen props that nobody dares touch.

This lesson gives you a method. We start with the principles (single responsibility, naming, props API design, when to extract), then apply a five-step process to build a searchable product table from a mock design. State is introduced only at the end, so if useState is new to you, skim that step and return after State with useState.

One component, one job

A component should do one thing you can name without using the word "and". ProductRow renders a row. SearchBar collects a query. A component called ProductTableAndFilterAndTotals is three components that have not been separated yet.

Some signals that a component has grown too big:

  • Its JSX is longer than a screen and has several unrelated visual regions.
  • It has many pieces of state that change for unrelated reasons.
  • You have copied a block of JSX and changed two words.
  • You cannot describe it in one sentence.
  • A change to one part forces you to re-test the whole thing.

The opposite mistake exists too: wrapping every <div> in its own component produces files full of one-liners that hide what the UI does. Extract when it earns something: reuse, clarity, or a place to put state.

When to extract a component

Three honest reasons, in order of strength:

  1. Repetition. The same markup appears in two places, or inside a .map() with real structure (a list row).
  2. A name makes the code clearer. Replacing 25 lines of markup with <PriceSummary items={items} /> documents intent.
  3. State or logic wants a home. A piece of UI with its own state (a dropdown that remembers if it is open) is a good component because the state then stays local: when it changes, only that component re-renders.

A good rule of thumb: when you notice a repeat for the second time, tolerate it; at the third, extract. Premature abstraction is more expensive than a little duplication, because wrong abstractions accumulate flags and special cases.

Naming

  • Components are PascalCase nouns: ProductRow, UserMenu, ErrorMessage. React treats lowercase tags as DOM elements, so the capital letter is required.
  • Name by role, not by appearance: PrimaryButton ages better than BlueButton; Alert better than RedBox.
  • Event-handler props start with on (onSelect, onClose); the functions you pass start with handle (handleSelect).
  • Boolean props read like a question: disabled, isOpen, hasError.
  • One main component per file, file name equal to the component name (ProductRow.jsx), and keep tiny helpers that nobody else uses in the same file.

Designing the props API

Props are the public interface of a component. Think of them the way you think of function parameters.

Keep the list short. More than five or six props usually means the component does too much or that related props should be grouped. Pass an object when values travel together (product instead of name, price, stocked, image), as long as the child really uses most of it.

Make the common case easy. Provide default values for options so the simplest usage is the shortest.

Prefer meaningful options over many booleans. Consider two designs of a button:

JSX
// Hard to read, and allows nonsense like both at once:
<Button primary danger small />

// Clear, and impossible to combine badly:
<Button variant="danger" size="small" />

Use children for content, props for configuration. Text and nested elements belong in children (<Button>Save</Button>); variant, size and disabled are configuration. When a component needs several distinct content slots, pass elements as props (see Children and Composition).

Design for controlled flexibility. Allow customization where it matters, and forward the rest. A reusable Field should let callers set a className or an id without you adding a prop for every attribute.

A small, well-shaped Button API

The defaults make <Button>Save</Button> the shortest form, variant and size take a fixed set of words, and ...rest forwards onClick, disabled, aria-label and friends to the real <button> without declaring each one. The type="button" default prevents accidental form submits; a caller who needs a submit button can override it because {...rest} comes last.

Spreading ...rest is convenient for thin wrappers around DOM elements. For components with their own rules, list the props explicitly so the API stays documented and typos are noticed.

Thinking in React: five steps

Now the method. Imagine a designer gives you a mock-up: a search box, a checkbox labelled "Only show products in stock", and a table of products grouped by category, with out-of-stock names in red. We will build it.

Step 1: Break the UI into a component hierarchy

Draw a box around each part and name it. The names often match the structure of your data or your design layers.

  • FilterableProductTable (the whole thing)
    • SearchBar (input and checkbox)
    • ProductTable (table, header row)
      • ProductCategoryRow (category heading)
      • ProductRow (name and price)

Each box has one job: the table renders rows, the search bar collects input.

Step 2: Build a static version

First build the UI from data using only props: no state, no interactivity. Building the static version is mostly typing; adding interactions is mostly thinking, so doing them separately keeps each step simple.

Step 2: the static product table

Data flows down as props; nothing here changes yet. Note the ProductTable loop pushes a category row whenever the category changes, which assumes the data is sorted by category. Both ProductCategoryRow and ProductRow have keys; see Rendering Lists and Keys.

Step 3: Find the minimal representation of state

Which data changes over time? Ask three questions about each piece of data. If any answer is yes, it is not state:

  1. Does it stay unchanged over time? (then it is a constant or prop)
  2. Is it passed in from a parent through props?
  3. Can you compute it from other state or props? (then it is derived; compute it during render)

Applying that: the product list is passed in (not state). The search text changes and cannot be computed: state. The checkbox value changes: state. The filtered list can be computed from the products, the text and the checkbox, so it is not state. Keep state minimal; duplicated, derived state leads to values that disagree with each other (more on this in Choosing a State Structure).

Step 4: Decide where state lives

Find every component that displays something using that state, and find their closest common parent. State lives there. Both SearchBar (shows the controls) and ProductTable (filters the rows) need the text and checkbox, and their closest common parent is FilterableProductTable. So it owns the two state variables, and passes values down together with setter callbacks.

Step 5: Add inverse data flow

The child that contains the input cannot change the parent's state directly. The parent passes a function down (onFilterTextChange) and the child calls it from its onChange. Data flows down as props; events flow up as callbacks.

Steps 3 to 5: state in the parent, events flowing up

Try typing "pea" and then ticking the checkbox. The filtered rows are computed during every render; no state holds them. SearchBar is a controlled component: its inputs show whatever the parent says (value, checked) and report edits upward. We study controlled inputs in Controlled Inputs and Forms and sharing state in Lifting State Up.

File organisation

For a lesson-sized app, one file is fine. In a real project, a few conventions prevent pain:

  • Co-locate what changes together: ProductTable.jsx, its CSS and its test live next to each other.
  • Group by feature (products/, cart/) rather than by kind (components/, hooks/, utils/) once an app grows; components used across features go to a shared/ or ui/ folder.
  • Keep one exported component per file for anything non-trivial, plus small private helpers underneath.
  • Avoid deeply nested folders and barrel files (index.js that re-exports everything) until you actually feel the pain, because they slow editors and bundlers.

See App Architecture for the larger picture.

Common design mistakes

  • Props that mirror state. Copying a prop into state (useState(props.value)) freezes the initial value; the child ignores later changes. Use the prop directly, or lift the state.
  • Components defined inside components. A function declared in a component body is a new component type on every render, so React throws away its DOM and state each time. Always declare components at the top level of the module.
  • Boolean explosion. Five independent booleans give 32 combinations, most meaningless. Replace them with one status or variant value.
  • Giant prop objects passed everywhere. If a leaf needs a single field, give it that field; otherwise every change to the object looks relevant to it.
  • Premature generalization. Build for today's use cases, and generalize when the third appears.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which sentence best describes a well-scoped component?

    A single responsibility keeps components small, testable and easy to name. Large catch-all components are the usual starting point for refactoring.
  2. 2. In the product table, why is the filtered list not stored in state?

    Data that can be calculated from existing state or props is derived data. Storing it separately would create a second source of truth that can go out of sync.
  3. 3. Where should state live when two sibling components both need it?

    Lift state to the closest common parent, which passes values down as props and receives changes through callback props.
  4. 4. What is wrong with writing function ProductRow() inside the body of another component?

    Each render of the outer component creates a different function, and React treats a different function as a different component type, so it unmounts and remounts the inner one.
  5. 5. Which API for a button is clearer and safer?

    A named variant picks one option from a fixed set, so impossible combinations cannot be written, and the call site documents itself.

Summary

  • Give each component one clear job; extract for repetition, clarity or to give state a local home.
  • Name components by role in PascalCase; handler props start with on, handlers with handle.
  • Design props like a function signature: few, meaningful, with good defaults, and children for content.
  • Thinking in React: split the UI into components, build a static version, find minimal state, place it in the closest common parent, add inverse data flow.
  • Derived data is computed during render, never stored in state.
  • Declare components at module level; do not copy props into state.

Next: Handling Events