Props vs State in React: Key Differences and When to Use Each
props are read-only inputs passed from parent to child components to configure them, while state is a local, mutable data store managed inside a component to handle dynamic changes. Props cannot be changed by the component receiving them, but state can be updated to trigger UI updates.Quick Comparison
Here is a quick side-by-side comparison of props and state in React.
| Factor | Props | State |
|---|---|---|
| Purpose | Pass data from parent to child | Manage local component data |
| Mutability | Read-only | Mutable |
| Ownership | Owned by parent component | Owned by the component itself |
| Update Method | Cannot be changed by child | Updated via setState or hooks |
| Triggers Re-render | Yes, when changed by parent | Yes, when updated internally |
| Usage Example | Configuring child component | Handling user input or UI changes |
Key Differences
Props are like parameters you pass to a function. They come from a parent component and cannot be changed by the child component receiving them. This makes props perfect for passing fixed data or callbacks down the component tree.
State, on the other hand, is like a component's own memory. It holds data that can change over time, such as user input or toggles. When state changes, React re-renders the component to reflect the new data.
While props are immutable inside the child, state is mutable and managed inside the component using hooks like useState. This difference defines how data flows and updates in React apps.
Code Comparison
This example shows how to use props to display a message passed from a parent component.
import React from 'react'; function MessageDisplay({ message }) { return <p>{message}</p>; } export default function App() { return <MessageDisplay message="Hello from props!" />; }
State Equivalent
This example shows how to use state inside a component to update a message when a button is clicked.
import React, { useState } from 'react'; export default function App() { const [message, setMessage] = useState('Hello from state!'); return ( <div> <p>{message}</p> <button onClick={() => setMessage('State updated!')}>Update Message</button> </div> ); }
When to Use Which
Choose props when you want to pass data or callbacks from a parent to a child component without allowing the child to change them. Use state when you need to track and update data inside a component that affects its rendering, like user input, toggles, or dynamic content.
In short, use props for fixed inputs and state for data that changes over time inside a component.