What are Props? What is State? Should I use props or state? What impact do they have? What is the difference between props and state?
Do you have these kinds of questions when you start working with React? Yes?
So let me tell you one thing, these are all relevant questions and clarity of these concepts will pay off in the long run while working with React
Let’s start with the basics!
Example
<Button type="alert" name="Quit" disabled={true}/>
In the above example all the attributes i.e type, name, disabled are all props
React Applications are formed by composing different components.
There are 2 types of component
State is a closure variable which is used for communication within a component
Having said that, Stateful components manipulate this state using setState() to modify the behavior of a component
However, when this internal state is passed to other components using props it becomes a Stateless component
Example
// Stateless Component
const DisplayDetails = props => {
return (
<div>
<h1> Props Usage </h1>
<h3>
My name is {props.firstName} {props.lastName}, I live in {props.city}.
Nice to meet you!!{" "}
</h3>
</div>
);
};
// Stateful Component
class Greet extends React.Component {
state = {
name: ""
};
updateName = e => {
if (e.key === "Enter" && e.target.value.trim().length != 0) {
this.setState({
name: e.target.value
});
}
};
render() {
return (
<div>
<h1> State Usage </h1>
{!this.state.name && (
<div>
<h3> What's your good name ?</h3>
<input
type="text"
onKeyPress={this.updateName}
placeholder="Once done press Enter"
/>
</div>
)}
{ this.state.name.trim().length != 0 && (
<h3> Hola !!! My name is {this.state.name}</h3>
)}
</div>
);
}
}
const userDetails = {
firstName: "Arwa",
lastName: "Lokhandwala",
city: "Mumbai"
};
ReactDOM.render(
<div>
<DisplayDetails {...userDetails} /> <hr />
<Greet />
</div>,
document.getElementById("root")
);
In the above example, DisplayDetails is a Stateless Component which receives custom data through props firstName, lastName & city
Greet Component, however, is a Stateful Component as it uses React’s State to store the _name _captured by onKeyPress event and then access it from the state using _this.state.name _to greet the user
So looking at the above example we can fairly conclude that,
State is a closure variable which is used for communication within a component> State is a closure variable which is used for communication within a component## So then, What is the difference between State & Props ?
Understanding everything above is a lot to grasp, hence let me help you with a few gotchas which you can quickly refer to
Thanks for reading ❤
If you liked this post, share it with all of your programming buddies!
#reactjs #javascript