React Object Destructuring

December 3, 2021 (3y ago)

Archive

Do not do this

export interface MyComponentProps {
  onClick: () => void;
  onAction: (action: Action) => void;
  state: State;
  title: string;
}

export function MyComponent({
  onClick,,
  onAction,
  state,
  titl,
}: MyComponentProps): ReactElement {
  return (
    <div>
      <h1>{title}</h1>
    </div>
  );
}

And definitely not this

export function MyComponent({
  onClick,,
  onAction,
  state,
  titl,
}: {
  onClick: () => void;
  onAction: (action: Action) => void;
  state: State;
  title: string;
}): ReactElement {
  return (
    <div>
      <h1>{title}</h1>
    </div>
  );
}

You're not in JS land anymore, so instead do this

export interface MyComponentProps {
  onClick: () => void;
  onAction: (action: Action) => void;
  state: State;
  title: string;
}

export function MyComponent(props: MyComponentProps): ReactElement {
  return (
    <div>
      <h1>{props.title}</h1>
    </div>
  );
}

Here's why

Reason 1: Readability

The biggest drawback is that it can obscure the readability of a component's signature. When a function has multiple parameters, it is harder to discern the purpose of each parameter. This can become even more confusing when ReactElement is not explicitly defined in an interface or type.

Reason 2: Performance

Property destructuring can create unnecessary object copies, this heavily impacts performance in large components.

Reason 3: Where it came from? What does it represent?

In large React components with complex state management. I want to understand where variables originate from. Using property destructuring obscures the source of a variable, this makes things more confusing that they have to, what is it? Is it a prop? state? event? parameter? Bird ? I don't know.

Reason 3: Reusability with Child Components and Functions

Do you really have to rebuild the whole object to pass it to a child component again? No

Reason 4: Name Conflicts with local variables

Reason 5: Complexity with Deep Nesting

Reason 6: No IntelliSense

Reason 7: DX