Ever felt like React is playing mind games with you? Props and State can seem like twins, but they serve very different purposes β and mixing them up can cause chaos in your components. π
Letβs break it down so you never get confused again! π
π§ Props: The Data You Pass Down
Think of props like care packages you send to components. They are:
- Read-only (immutable)
- Passed from parent to child
- Great for static or external data
πΉ Example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
Here, name is a prop β and the component canβt change it.
π Tip: Use props for anything that shouldnβt change within a component (like config values or content).
π’ State: The Data You Control
State is like the inner mood of a component β it lives inside and can change over time. Itβs perfect for:
Dynamic data (like form inputs)
User interactions
Component lifecycle changes
πΉ Example:
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Here, count is state β and the component can change it with setCount.
β‘ Key Differences (In Simple Terms)
Props = Data IN (from parent) π¨
State = Data OUT (componentβs private data) π€
Props are fixed unless the parent component changes them.
State is flexible and can change within the component itself.
π¨ Common Mistake: Donβt try to modify props inside a component. If you need to change data, lift the state up and pass it back down as a prop!
π Quick Analogy:
Imagine a vending machine π₯€
Props = The snacks inside the machine (supplied by the owner)
State = The current stock count of each snack (tracked by the machine itself)
If you buy a snack, state updates, but the props stay the same until the owner refills the machine.
π¬ Are you handling props and state like a pro, or have you had any "aha!" moments while learning React?
Let me know in the comments! π
π Follow DCT Technology for more hands-on web development tips and tricks!
Top comments (1)
Props is give a pure component solution because we can avoide the inner state.
Props working as state, to modify we need to use that state set method.
That why I write a npm module: react type safe useReducer to easy make a typesafe useReducer solution which is work:
Panel and OtherPanel can use any state, and actions to handle our ParentComponent
Technically we can pass whole actions to safe because that is don't change on run. A lower component level we can select which state pass it to it.
But I am moving fare away from React, but this simple solution can save my days a lot. The problem is writing a good reducer is takes a times.