Most frequently asked questions (FAQs) about props in React, especially useful for interviews or practical learning:
🔹 1. What are props in React?
Answer:
Props (short for “properties”) are read-only inputs to a React component. They are used to pass data from a parent component to a child component.
🔹 2. How are props different from state?
Answer:
Props | State |
---|---|
Passed from parent to child | Managed inside the component |
Read-only | Can be changed (using setState or useState ) |
Immutable | Mutable |
🔹 3. Can props be changed inside a child component?
Answer:
No. Props are read-only. If you want to change data, you must ask the parent to update it (usually by calling a function passed down via props).
🔹 4. What type of data can be passed as props?
Answer:
Almost anything:
- Strings
- Numbers
- Booleans
- Arrays
- Objects
- Functions
- React components
Example:
<ProductItem
product={{ id: 1, name: "Cat Toy" }}
onAddToCart={handleAddToCart}
/>
🔹 5. How to pass functions using props?
Answer:
You can pass a function from parent to child, then call it inside the child.
// Parent
<ProductItem onClick={() => alert("Clicked!")} />
// Child
function ProductItem({ onClick }) {
return <button onClick={onClick}>Click</button>;
}
🔹 6. What is children
in props?
Answer:props.children
is a special prop that represents the content inside a component’s opening and closing tag.
Example:
<MyCard>
<p>This is child content!</p>
</MyCard>
In MyCard
, props.children
will be the <p>...</p>
.
🔹 7. What happens if a required prop is missing?
Answer:
The component might break or show unexpected behavior. You can use PropTypes or TypeScript to enforce required props.
🔹 8. Can props be defaulted?
Answer:
Yes, using defaultProps
or default values in the function signature.
function ProductItem({ name = "Unknown" }) {
return <div>{name}</div>;
}
🔹 9. Why should we keep props immutable?
Answer:
Because React relies on predictable updates. Mutating props can break re-rendering and cause bugs.
🔹 10. Can I destructure props in the function argument?
Answer:
Yes! It’s common practice:
function ProductItem({ product, onAddToCart }) {
return <div>{product.name}</div>;
}
Comments are closed.