React

Lesson 01

Props component boundaries

Keep presentational components focused by passing the data they need explicitly.

Good Code

ReviewSummary.tsx
type ReviewSummaryProps = {
  title: string;
  reviewerName: string;
  status: "approved" | "changes-requested";
};

export function ReviewSummary({
  title,
  reviewerName,
  status,
}: ReviewSummaryProps) {
  // Explicit props make this component easy to move and test.
  return (
    <section>
      <h2>{title}</h2>
      <p>{reviewerName} marked this review as {status}.</p>
    </section>
  );
}

Bad Code

ReviewSummary.tsx
import { useAppState } from "./app-state";

export function ReviewSummary() {
  // Hidden app-state reads make the component depend on too much.
  const { currentProject, activeReview, viewer } = useAppState();

  return (
    <section>
      <h2>{currentProject.name}: {activeReview.title}</h2>
      <p>{viewer.name} marked this review as {activeReview.status}.</p>
    </section>
  );
}

Review Notes

What to review

Good Code

The good version makes the component boundary obvious: the component receives the display values it needs and renders them.

Bad Code

The bad version reaches into broad application state, which couples a reusable summary to unrelated project, review, and viewer concerns.

Takeaways

  • Prefer explicit props for presentational components over hidden app-state reach-ins.