Props and State (Live Playground)
In React, components can manage and receive data through two mechanisms: props and state. Understanding the difference between props and state is crucial for building efficient and maintainable React applications. In this tutorial, we'll explore the concepts of props and state with examples.
Props
Props (short for properties) are the data passed down from a parent component to a child component. They are read-only, meaning that a component should never modify its props.
Here's an example of passing props to a functional component:
import React from 'react';
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default Greeting;
And here's the same example using a class component:
import React from 'react';
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
export default Greeting;
In both examples, the Greeting
component receives a name
prop from its parent component and renders it inside an h1
element.
State
State represents the internal data of a component that can change over time. In class components, you can manage state using the this.state
object and the this.setState()
method. In functional components, you can manage state using the useState
hook.
Here's an example of managing state in a functional component:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
And here's the same example using a class component:
import React from 'react';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
</div>
);
}
}
export default Counter;
In both examples, the Counter
component manages its state with a count
variable and a button to increment the count.
Conclusion
Understanding the difference between props and state is essential for building efficient and maintainable React applications. Props are read-only data passed down from parent components, while state is the internal data of a component that can change over time. React provides different mechanisms for managing state in functional and class components, such as the useState
hook and the setState()
method.