Part 02 / Topic 5 of 7
Props are read-only - a real bug, not a theoretical rule
React's docs state components must treat props "as read-only." This course could leave that as an abstract rule, but it is far more convincing as a bug you actually cause and then fix. examples/03_props_are_read_only.jsx has two functions that both claim to "sort a list of products cheapest-first":
// examples/03_props_are_read_only.jsx
export function sortCheapestFirstBroken(products) {
// `.sort()` sorts the array IN PLACE and returns that same reference.
return products.sort((a, b) => a.price - b.price);
}
export function sortCheapestFirstFixed(products) {
// Copy first with the spread operator, then sort the copy.
return [...products].sort((a, b) => a.price - b.price);
}
Array.prototype.sort mutates the array it is called on and returns that same array - a detail of the built-in method, not anything React adds. Calling the broken version on a products array and then looking at that same array variable afterward really shows it reordered too (examples/03_props_are_read_only.test.jsx, actually run):
before: Ghee 500ml, Atta 5kg, Toor Dal 1kg
after: Toor Dal 1kg, Atta 5kg, Ghee 500ml
Nothing printed a warning. Nothing threw an error. If that array had been a prop - say, a products array a parent component is still rendering its own list from - the parent's list would silently reorder itself the moment some unrelated child "just sorted a copy for a banner." The fixed version spreads the array into a brand-new one first, so the sort has nothing to mutate that the caller still holds a reference to; the original array's order is provably untouched afterward. ProductList, in the same file, only ever reads products and calls the fixed sorter - it never reassigns or mutates the prop it received, which is the entire rule, stated as code instead of a sentence: read from a prop as much as you like; never write to it.
๐ Going deeper: this is exactly why
useState(Part 3) exists instead of "just mutate a prop or a plain variable and re-render": React needs to know a value changed in order to decide whether to re-render, and it finds out by comparing a new value to the old one. Mutating in place gives React nothing new to compare against.
Done here? The practice set for Part 2 โ including the solutions โ is on the part page.