Difference between props and state
PROPS | STATE |
---|---|
The Data is passed from one component to another. | The Data is passed within the component only. |
It is Immutable (cannot be modified). | It is Mutable ( can be modified). |
Props can be used with state and functional components. | The state can be used only with the state components/class component (Before 16.0). |
Props are read-only. | The state is both read and write. |
In conclusion, the main significant difference between states and props is that props are used to transfer data from a parent component to a child whereas states are used to manage the data inside a component itself.
Let us see an the example where we can properly understand the difference between state props
Create a React application with the command
npx create-react-app statevsprop
and write the below code in index.js file of your application
Example:
// Filename - index.js
import React, { Component } from "react"
import ReactDOM from 'react-dom';
import './index.css';
const Fruit = (props) => {
return (
<div className="fruit">
<h1>List of Fruits</h1>
<p>Name: {props.fruits.name}</p>
<p>Color: {props.fruits.color}</p>
</div>
)
}
class Car extends Component {
constructor() {
super()
this.state = {
car: 'Ferrari'
}
}
changeMessage() {
this.setState({
car: 'Jaguar'
})
}
render() {
return (
<div className="App">
<h1>{this.state.car}</h1>
<button onClick={() => this.changeMessage()}>
Change
</button>
</div>
)
}
}
function App() {
const fruits =
{
name: "Mango",
color: "Yellow"
}
return (
<div className="App">
<Fruit fruits={fruits} />
<hr></hr>
<Car />
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Output: In the fruit component props are used where data is passed by the parent component(App) to child(Fruit) whereas the car component manages data internally using state
Note: To know about the difference you can check this What are the differences between props and state.
ReactJS State vs Props
In React props are a way to pass the data or properties from parent component to child components while the state is the real-time data available to use within that only component.
States and props are two of the most important concepts of React and everything in React is based upon them. But before jumping into State and Props we need to know about the relation between components and normal functions.
Table of Content
- Relation between Components and normal functions in JavaScript
- State in React
- Props in React
- Difference between props and state