What is prop spreading and when is it an anti-pattern?

MediumAdvanced PatternsTheory Question

Hint

{...props} forwards all props — useful for wrapper components but can pass wrong props to DOM elements

Full Answer

// ✅ Legitimate use — forwarding unknown props to underlying element
function Button({ variant, className, ...rest }) {
  return (
    <button
      className={`btn btn-${variant} ${className}`}
      {...rest}  // forwards onClick, disabled, type, aria-*, etc.
    />
  );
}

// ❌ Anti-pattern 1 — unknown DOM attributes cause React warnings
function Box({ color, ...rest }) {
  return <div {...rest} />; // if 'color' is in rest, "Unknown prop 'color'" warning
}

// ✅ Fix — destructure all custom props, only spread standard ones
function Box({ color, size, children, ...htmlProps }) {
  return <div style={{ color }} {...htmlProps}>{children}</div>;
}

// ❌ Anti-pattern 2 — spreading all parent props down
function Parent(props) {
  return <Child {...props} />; // leaks parent-specific props to child
}

// ❌ Anti-pattern 3 — security risk with user-provided data
// If attackers control the props object, they could inject onClick etc.
const userConfig = JSON.parse(untrustedInput);
<Component {...userConfig} /> // dangerous!
💡 Always destructure custom props before spreading. "Rest" in a component should only contain valid HTML attributes for the element it spreads onto.

More Advanced Patterns Questions

Practice this in a timed sprint

5 free questions, no signup required