How is state different than props in React?
Answer
In React, both state and props are used to manage data in a component. However, they differ in their functionality and usage.
Props are short for properties, and they are used to pass data from a parent component to a child component. They are immutable, meaning that they cannot be changed within the child component. Props are passed down as an argument to the child component and can be accessed using the 'this.props' syntax. Props are useful when we want to reuse a component with different data. For example, if we have a 'Person' component, we can pass different names and ages as props to create different instances of the component.
State, on the other hand, is used to manage data within a component. It is mutable, meaning that it can be changed within the component. State is initialized within the constructor of a component and can be accessed using the 'this.state' syntax. State is useful when we want to update the data within a component based on user interactions or other events. For example, if we have a 'Counter' component, we can use state to keep track of the current count and update it when the user clicks a button.
// Example of using props and state in a component
class Person extends React.Component {
constructor(props) {
super(props);
this.state = {
age: this.props.age
};
}
handleClick = () => {
this.setState({ age: this.state.age + 1 });
}
render() {
return (
<div>
<p>Name: {this.props.name}</p>
<p>Age: {this.state.age}</p>
<button onClick={this.handleClick}>Increase Age</button>
</div>
);
}
}
// Usage of the Person component with different props
<Person name="John" age={25} />
<Person name="Jane" age={30} />
Related React job interview questions
What is uncontrolled component in React?
React JuniorWhat is a controlled component in React?
React JuniorWhat are props in React?
React JuniorWhat is mounted component in React?
React JuniorWhich methods would you use to handle events in React?
React Junior