Good Code
The good version derives the count from the current reviewers prop during render, so there is only one source of truth.
Lesson 03
Compute values from current props and state instead of syncing duplicates.
type Reviewer = {
id: string;
name: string;
approved: boolean;
};
export function ReviewerList({ reviewers }: { reviewers: Reviewer[] }) {
// Derived values can be computed from current props during render.
const approvedCount = reviewers.filter((reviewer) => reviewer.approved).length;
return <p>{approvedCount} of {reviewers.length} reviewers approved.</p>;
}import { useEffect, useState } from "react";
type Reviewer = {
id: string;
name: string;
approved: boolean;
};
export function ReviewerList({ reviewers }: { reviewers: Reviewer[] }) {
const [approvedCount, setApprovedCount] = useState(0);
// Duplicated state needs an effect just to stay synchronized.
useEffect(() => {
setApprovedCount(reviewers.filter((reviewer) => reviewer.approved).length);
}, [reviewers]);
return <p>{approvedCount} of {reviewers.length} reviewers approved.</p>;
}The good version derives the count from the current reviewers prop during render, so there is only one source of truth.
The bad version stores a duplicate count and then uses an effect to keep it synchronized with props.