- What is Props?
- Props stands for Properties in React.
- Props are used to pass data from one component to another, usually from a parent component to a child component. -Props are read-only, meaning the child component cannot change them.
Simple definition:
Props allow components to communicate with each other by sending data.
2 Why Do We Need Props?
- React follows a component-based architecture.
- Each component should be independent and reusable.
Props help us to:
- Share data between components
- Reuse the same component with different values
- Keep code clean and organized
β Without Props
You would have to hardcode values inside components.
β With Props
You can pass dynamic data easily.
3.How Props Work?
Props always work in one direction:
Parent β‘ Child
Step 1: Pass Props from Parent Component
function App() {
return <Welcome name="Kiran" />;
}
Here:
- name is a prop
- "Kiran" is the value
Step 2: Receive Props in Child Component
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Output:
Hello, Kiran
- Destructuring Props
function Welcome({ name }) {
return <h1>Hello, {name}</h1>;
}
- This is the most commonly used method.
π· Props Are Read-Only
You cannot change props inside a child component.
β Wrong:
props.name = "Raj";
β Correct:
- Props should only be used, not modified
- If data needs to change β use state
4.Where Are Props Used?
Props are used whenever data needs to be shared between components.
πΉ Common Use Cases
1οΈβ£ Passing Text
<Button label="Submit" />
2οΈβ£ Passing Numbers
<Counter start={10} />
3οΈβ£ Passing Functions
<Button onClick={handleClick} />
4οΈβ£ Passing Objects
<User user={{ name: "Kiran", age: 24 }} />
π· Props vs State (Quick Comparison):
| Props | State |
|---|---|
| Passed from parent | Managed inside component |
| Read-only | Can be changed |
| Used for communication | Used for data changes |
| Immutable | Mutable |
π· Real-World Example :
Think of props like arguments in a function.
function greet(name) {
return "Hello " + name;
}
React version:
<Greet name="Kiran" />
Same idea, different syntax.
π· Conclusion β¨
Props:
- Help pass data between components
- Make components reusable
- Improve code structure and readability
Top comments (0)