In React, State and Props are two fundamental concepts that help manage data and behavior within components.
Explanation of Key Concepts
Props
State
Step-by-Step Solution
To illustrate the difference between props and state:
function Parent() {
return (
<div>
<Child name='John' age={30} />
</div>
);
}
2. Pass props to the child component: The Parent
component is passing an object with two properties (name
and age
) to its child component.
3. Use state in the child component: Now, let's update the Child
component to use state instead of props.
function Child() {
const [name, setName] = useState('John');
const [age, setAge] = useState(30);
return (
<div>
<h2>Hello, {name}!</h2>
<p>You are {age} years old.</p>
</div>
);
}
4. Update the state in the child component: Now we can update the state in the Child
component to reflect some changes.
function Child() {
const [name, setName] = useState('Jane');
const [age, setAge] = useState(25);
return (
<div>
<h2>Hello, {name}!</h2>
<p>You are {age} years old.</p>
</div>
);
}
Example
Here's a simple example of using state and props in React:
import React, { useState } from 'react';
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<Child name='John' age={30} />
</div>
);
}
function Child(props) {
return <h2>Hello, {props.name}!</h2>;
}
In this example, the Parent
component uses state to store and update its own data (the count). The Child
component receives props from the Parent
component but does not use state.
Conclusion
To summarize, Props are used for passing read-only values between components, while State is used for storing dynamic data within a component.