ReactJS State vs Props
Syntax
Defining props
class MyComponent extends React.Component {
render() {
return <h1>{this.props.title}</h1>;
}
}
ReactDOM.render(<MyComponent title="Hello, World!" />, document.getElementById('root'));
Defining state
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
</div>
);
}
}
ReactDOM.render(<MyComponent />, document.getElementById('root'));
Example
Component using Props
class MyComponent extends React.Component {
render() {
const { title, subtitle } = this.props;
return (
<div>
<h1>{title}</h1>
<h2>{subtitle}</h2>
</div>
);
}
}
ReactDOM.render(<MyComponent title="Hello, World!" subtitle="Welcome to ReactJS" />, document.getElementById('root'));
Component using State
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
const { count } = this.state;
return (
<div>
<h1>{count}</h1>
<button onClick={() => this.setState({ count: count + 1 })}>Increment</button>
</div>
);
}
}
ReactDOM.render(<MyComponent />, document.getElementById('root'));
Explanation
Props
Props are short for properties, and they are used to pass data from one component to another. They are immutable, which means that they cannot be changed once they are set. They are similar to function arguments.
State
State is used to manage the changes in the component, and it is mutable, which means that it can be changed. State is used to store the data that can be changed within the component.
Use
Props are used to pass data from a parent to child component. State is used to manage the changes within the component itself.
Important Points
- Props are immutable, while state is mutable.
- Props are used to pass data from parent to child component, while state is used to manage the changes within a component.
- State can only be modified with the setState() method, while props cannot be modified at all.
Summary
Props and state are important concepts in ReactJS, and they are used in different ways. Props are used to pass data from one component to another, while state is used to manage the changes within a component. Props are immutable, while state is mutable. State can be changed using the setState() method, while props cannot be changed at all.