SyntaxStudy
Sign Up
React Destructuring Props and Default Values
React Beginner 1 min read

Destructuring Props and Default Values

Destructuring props directly in the function signature is the idiomatic React style. Instead of accessing `props.name`, `props.age`, and so on throughout the function body, you extract each value at the parameter level: `function User({ name, age })`. This makes the component's interface immediately visible at the top of the file and reduces repetitive `props.` prefixes. Default parameter values, written with `= value` in the destructuring pattern, define fallbacks for optional props. When a consumer omits an optional prop entirely, the default is used; when the prop is explicitly passed, the passed value wins. Default values replace the older `Component.defaultProps` pattern and are evaluated lazily, which means they can reference other default values in the same parameter list. Renaming during destructuring is another useful technique: `function Avatar({ src: imageSrc })` extracts `props.src` and binds it locally as `imageSrc`. This is handy when a prop name would clash with a local variable or when you want a more descriptive internal name. Combining destructuring, defaults, and renaming creates self-documenting component signatures that serve as informal API documentation.
Example
// Destructuring with defaults — the idiomatic React style
function Avatar({
  src,
  alt = 'User avatar',
  size = 48,
  shape = 'circle',  // 'circle' | 'square'
}) {
  const radius = shape === 'circle' ? '50%' : '6px';
  return (
    <img
      src={src}
      alt={alt}
      width={size}
      height={size}
      style={{ borderRadius: radius, objectFit: 'cover' }}
    />
  );
}

// Renaming a prop internally
function Link({ href: url, children, external = false }) {
  const extraProps = external ? { target: '_blank', rel: 'noopener noreferrer' } : {};
  return <a href={url} {...extraProps}>{children}</a>;
}

// Rest props — forward unknown props to underlying element
function Input({ label, id, ...rest }) {
  return (
    <div>
      <label htmlFor={id}>{label}</label>
      <input id={id} {...rest} />
    </div>
  );
}

// Usage
function App() {
  return (
    <div>
      <Avatar src="/alice.jpg" size={64} />
      <Avatar src="/bob.jpg" shape="square" alt="Bob's photo" />
      <Link href="https://react.dev" external>React Docs</Link>
      <Input label="Email" id="email" type="email" placeholder="you@example.com" />
    </div>
  );
}

export default App;