Props vs State
Props vs State
In React, both props and state are plain JavaScript objects that hold information that influences the output of render, but they are fundamentally different in how they are used.
Props (Properties)
- Definition: Arguments passed into a component.
- Mutability: Immutable (read-only). A component cannot change its own props.
- Ownership: Owned and managed by the parent component.
- Analogy: Parameters passed to a function.
// The child component receives the 'name' prop
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
// The parent passes the 'name' prop down
function App() {
return <Greeting name="Alice" />;
}
State
- Definition: Data managed within a component.
- Mutability: Mutable (can be changed using a setter function like
setStateorsetCount). - Ownership: Owned and managed by the component itself (local).
- Analogy: Variables declared within a function.
function Counter() {
// 'count' is internal state, starting at 0
const [count, setCount] = useState(0);
return (
// We can change our own state!
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
Summary Comparison
| Feature | Props | State |
|---|---|---|
| Can get initial value from parent Component? | Yes | Yes |
| Can be changed by parent Component? | Yes | No |
| Can be changed by the Component itself? | No | Yes |
| Can set initial value for child Components? | Yes | Yes |
A common pattern is to have a parent component manage state, and pass that state down to child components as props. When the child needs to update the state, the parent passes down a callback function as a prop, which the child can call.
Interview Questions
Q: What is the core architectural difference between Props and State?
A: Props are external, read-only data passed downwards from a parent to a child component. State is internal, mutable data created and managed completely within the component itself.
Q: Can a child component modify its own props?
A: Absolutely not. Props are strictly immutable in React to enforce unidirectional data flow. If a child needs to change a value passed via props, the parent must pass down a callback function (e.g., setCount) as a prop, which the child can call to request the parent to change its own state.