Frontend Patterns

Pattern

Props and Attributes

Pass data and configuration into components through properties or attributes.

Component Beginner

Props and Attributes

Problem

Components hardcode their data and behavior, making them impossible to reuse across different contexts. Every variation requires duplicating the entire component, and testing becomes painful because you can’t easily inject different values to verify edge cases.

Solution

Distinguish between JavaScript properties and HTML attributes when building components. This prevents confusion about how values are passed and ensures proper handling of both.

Example

This example shows a reusable button component that accepts configuration through props, making it adaptable to different contexts with different labels, handlers, and states.

// Button component accepts props for customization
function Button({ label, onClick, disabled = false }) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
    >
      {label}
    </button>
  );
}

// Same component can be used in different ways with different props
<Button label="Click me" onClick={handleClick} disabled={false} />

Benefits

  • Makes components reusable by accepting configuration through props.
  • Simplifies testing by allowing easy injection of different values.
  • Enables composition where components can be configured for different contexts.
  • Creates clear, predictable component interfaces.

Tradeoffs

  • Can lead to prop explosion when components become too configurable.
  • May complicate component internals with conditional logic based on props.
  • Requires careful API design to balance flexibility and simplicity.
  • Can make components harder to understand with many configuration options.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.