Frontend Patterns

Pattern

Default Props

Define fallback values for optional component inputs to ensure predictable behavior.

Component Beginner

Default Props

Problem

Components crash with “Cannot read property of undefined” errors when optional properties aren’t provided. Every consumer has to remember to pass values for optional properties, and the component behaves unpredictably across different usage contexts, forcing defensive null checks throughout the code.

Solution

Provide fallback values for optional component properties so consumers can omit them when defaults are acceptable. This reduces boilerplate in common cases while allowing customization when needed.

Example

This example demonstrates default parameter values that provide sensible fallbacks when props are not provided.

// Function parameters with default values for optional props
function Button({ label = 'Click me', variant = 'primary' }) {
  return <button className={variant}>{label}</button>;
}

// Uses default values: label="Click me" and variant="primary"
<Button />

Benefits

  • Reduces boilerplate by not requiring every consumer to pass optional props.
  • Prevents undefined errors when optional props are omitted.
  • Makes component behavior more predictable with sensible defaults.
  • Simplifies component API by clearly distinguishing required vs optional props.
  • Enables progressive customization where basics work out of the box.

Tradeoffs

  • Can hide important configuration if defaults are too magical.
  • May encourage passing too few props leading to implicit coupling.
  • Defaults can become outdated as requirements evolve.
  • Can make it harder to identify which props are actually being used.
  • May conflict with TypeScript strict null checks if not properly typed.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.