5. Props
Understanding Props and Immutable Data Flow
In React, components are the building blocks of your user interface, and props (short for properties) are the mechanism through which data travels between them. Think of a React component as a function in JavaScript; props are the arguments passed into that function. When a parent component renders a child, it passes down information that the child will use to decide what to display. One of the most important rules you must memorize as a VoidX recruit is that props are read-only. This is referred to as immutability. If you receive a property from a parent, you are strictly forbidden from modifying it within the child component. If you attempt to reassign a prop value, the React reconciler will not trigger a re-render because the data source (the parent) remains unchanged. This uni-directional data flow ensures that your application state remains predictable, making debugging much simpler since you know exactly where a piece of data originated.
const UserCard = (props) => { // Attempting to do props.name = 'New Name' will fail or cause unexpected side effects return <div>Welcome, {props.name}
In this code, props is an object containing every attribute passed to the component. The props.name property is extracted and injected directly into the JSX. If this component is used in App.tsx, the parent controls the data; the UserCard is merely a presentation layer.
Accessing Props and Destructuring Patterns
As you scale your project, referencing props.user.name or props.user.age repeatedly can become verbose and error-prone. This is why professional React developers utilize JavaScript destructuring. By destructuring the props object directly in the function signature, you make your component code significantly cleaner and easier to read. Additionally, we often use TypeScript interfaces to define the shape of our props. This provides autocomplete support in your code editor (like VS Code), ensuring you never pass the wrong data types—such as passing a string where a number is expected.
interface ButtonProps { label: string; count?: number; onClick: () => void; } const CustomButton = ({ label, count = 0, onClick }: ButtonProps) => { return ( <button onClick={onClick}> {label}: {count} </button> ); };
Line-by-line breakdown: The ButtonProps interface explicitly defines the contract for the component. label is a mandatory string. count is marked with a ?, indicating it is an optional parameter. We provide a default value of 0 using the assignment operator = 0 within the destructuring signature, which handles cases where the parent neglects to pass that specific prop. This is a robust pattern for preventing undefined errors in your UI logic.
Communication via Function Props and Children
In React, data flows unconditionally downwards. But how does a child communicate back to a parent? The answer is Function Props (often called callbacks). By passing a function reference from the parent to the child, the child can invoke it with arguments, effectively sending data upstream.
Furthermore, the children prop is a specialized prop automatically passed to every component. It contains whatever is placed between the opening and closing tags of the component invocation. This is crucial for creating wrapper components, such as Dialogs, Cards, or Layouts, where the parent doesn't need to know the exact content of the child ahead of time. The children prop can be a string, a React element, an array of elements, or even a function (Render Props pattern).
Edge Cases and Rules:
- Never invoke the function immediately in the event handler like
onClick={handleAction()}. This will execute the function on render. Always pass the reference:onClick={handleAction}or use an arrow function:onClick={() => handleAction(data)}. - When passing children, be aware that React provides a utility API
React.Children.mapif you need to inspect or modify the children before rendering, though this is an advanced pattern.
function Parent() { // Parent holds the state or logic const handleAction = (msg) => console.log('Child says:', msg); return ( <Card onAction={handleAction}> <h4>Notice me!</h4> <p>I am passed as the children prop.</p> </Card> ); } // Child receives the function and the special 'children' prop function Card({ onAction, children }) { return ( <div className="card-container"> {/* Render whatever the parent nested inside */} <div className="card-body">{children}
Knowledge Check
Ready to test your understanding of 5. Props?