Props
Props
React components use props (short for “properties”) to communicate with each other. Every parent component can pass some information to its child components by giving them props.
Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions.
Passing Props to a Component
To pass props, add them to the JSX, just like you would with HTML attributes.
export default function Profile() {
return (
<Avatar
person={{ name: 'Lin Lanying', imageId: '1bX5QH6' }}
size={100}
/>
);
}
Reading Props Inside a Component
You can read these props by listing their names separated by commas inside ({ and }) directly in the function signature. This is using JavaScript object destructuring.
function Avatar({ person, size }) {
return (
<img
className="avatar"
src={getImageUrl(person)}
alt={person.name}
width={size}
height={size}
/>
);
}
Alternatively, you can accept the entire props object and access properties using dot notation:
function Avatar(props) {
let person = props.person;
let size = props.size;
// ...
}
Props are Read-Only
Props are immutable. When a component needs to change its data in response to a user interaction (like a button click or a network response), it will need to use state instead of props. A component must never modify its own props.
function Clock({ time }) {
// ❌ BAD: Do not modify props!
time = time + 1;
return <h1>{time}</h1>;
}
Interview Questions
Q: What is “Prop Drilling”?
A: Prop drilling occurs when you have to pass data through multiple layers of intermediate components that don’t actually need the data, just to reach a deeply nested child component that does. It makes the code brittle and hard to maintain. It is usually solved by Context API, State Management libraries, or Component Composition.
Q: Are props limited to primitive strings and numbers?
A: No. You can pass literally any JavaScript data type via props: objects, arrays, callback functions, Promises, and even raw JSX / React Components.