📝 React Blog: Understanding State and Props with Examples
🔹 What are Props in React?
Props (short for properties) are used to pass data from parent components to child components. They are read-only, meaning a component cannot change the props it receives.
✅ Props Example
const App = () => {
return (
<div>
<h1>Props Example</h1>
<Greeting name="Anjum" />
</div>
);
};
const Greeting = ({ name }) => {
return <h2>Hello, {name}!</h2>;
};
Explanation:
The App component passes name="Anjum" to Greeting.
Greeting receives name via props and displays “Hello, Anjum!”.
🔹 What is State in React?
State is a built-in object that allows components to track changes over time. Unlike props, state is mutable and local to the component.
✅ State Example
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<h1>State Example</h1>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click Me
</button>
</div>
);
};
export default Counter;
Explanation:
useState(0) initializes count to 0.
When the button is clicked, setCount updates the state, re-rendering the component.
🔁 Props + State Combined Example
const App = () => {
return (
<div>
<h1>Combined Example</h1>
<User name="Aisha" />
</div>
);
};
const User = ({ name }) => {
const [likes, setLikes] = React.useState(0);
return (
<div>
<h2>Hello, {name}</h2>
<p>{name} has {likes} likes</p>
<button onClick={() => setLikes(likes + 1)}>
Like
</button>
</div>
);
};
Takeaways:
App passes name="Aisha" via props.
User uses useState to track likes. Each click increases likes for Aisha.
🧠 Conclusion
| Props | State |
|---|---|
| Passed from parent | Local to component |
| Read-only | Mutable |
| Used for communication | Used for internal changes |
| Received via function parameters | Managed via useState() |
