Sub topic 2
Why Props Are Read-Only
Assume you know JavaScript functions, objects, destructuring, JSX, and basic React components. A prop is an input that a parent gives to a child. React treats that input as read-only: the child may read it, but must not assign to it or mutate an object received through it.
function Profile({ user }) {
user.name = 'Changed'; // Do not do this.
return <p>{user.name}</p>;
}Mutation makes ownership unclear and can create inconsistent screens. The parent still owns user, so it should decide how user changes. A child requests a change by calling a function supplied by the parent.
Treat nested objects and arrays in props as read-only too. Create a new value and ask the owner to replace the old value.Nesting Content with `children`
JSX between a component's opening and closing tags becomes the children prop. This supports wrapper components without making the wrapper know the exact content.
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
<Card title="Account">
<p>Signed in as Ada.</p>
</Card>children can be text, one element, or an array of elements. The Card controls the layout, while its parent supplies the content.
Sending Events Upward with Callback Props
A callback prop is a function passed from parent to child. The child calls it when something happens. This sends an event request upward without giving the child ownership of the data.
import { useState } from 'react';
function LikeButton({ onLike }) {
return <button onClick={onLike}>Like</button>;
}
export default function Post() {
const [likes, setLikes] = useState(0);
return (
<>
<p>{likes} likes</p>
<LikeButton onLike={() => setLikes(likes + 1)} />
</>
);
}Props Versus State
State is data a component owns and can update with a state setter. Props are data a component receives and cannot update directly. Keep each piece of state in the component that owns the decision. Pass its current value down and pass callbacks down when children need to request changes.
This one-way flow makes updates easier to trace. If several distant components need the same data, consider composition or context instead of passing props through unrelated components.
Exercise
A child receives items and needs to add an item. Should it call items.push(newItem)?
Show answer
No. The child should call a callback prop, such as onAdd(newItem). The parent can create a new array and update its state.