Quick Summary:
You need to familiarize yourself with many different React elements to develop outstanding React web applications. Props and State are at the core of React development. Most developers often confuse the two terms and their functionalities. Here is a detailed comparison between React State vs Props for all you need to know:
React is one of the most popular web app frameworks globally for creating appealing and robust modern web apps for businesses. Since it is an open-source JavaScript-based framework, many developers are also drawn toward learning React.
Even though the learning curve with React is comparatively lower than most frameworks, some essential React concepts even seasoned React developers need help with at times. Two important concepts essential to React development are React Props vs. the React State. Many developers confuse the two or use the terms interchangeably, which is incorrect. They work together to achieve many benefits for React development. However, they are fundamentally different concepts. Before we understand the differences between React Props and State, we should understand these concepts individually first:
Props (abbreviation for Properties) are arguments you pass to React components. They are passed through HTML templates and are a method to pass data from one component to another. Props can be compared to functional arguments. They are passed to the component in the same manner arguments are passed in a function.
Let us understand how props work step by step:
Adding a “brand” attribute to the Bike element:
const myelement = <Bike brand="Harley Davidson" />;
Add the brand attribute in the component:
function Bike(props) {
return <h2> I am a { props.brand } !</h2>;
}
Pass the “brand” property from the Garage component to the Bike component:
function Bike(props) {
return <h2>I am a {props.brand}!</h2>;
}
function Garage() {
return (
<>
<h1>Which bike do I have in my garage?</h1>
<Bike brand="Harley Davidson" />
</>
);
}
ReactDOM.render(<Garage />, document.getElementById("root"));
If you need to send a variable instead of a string, you need to create a variable named bikeName and send it to the Bike component:
function Bike(props) {
return <h2>I am a {props.brand}!</h2>;
}
function Garage() {
const bikeName = "Harley Davidson";
return (
<>
<h1>Which bike do I have in my garage?</h1>
<Bike brand={bikeName} />
</>
);
}
ReactDOM.render(<Garage />, document.getElementById("root"));
Create an Object named bikeInfo and send it to the Bike component:
function Bike(props) {
return <h2>I am a {props.brand.model}!</h2>;
}
function Garage() {
const bikeInfo = { name: "Harley Davidson", model: "Street Glide" };
return (
<>
<h1>>Which bike do I have in my garage?</h1>
<Bike brand={bikeInfo} />
</>
);
}
ReactDOM.render(<Garage />, document.getElementById("root"));
A state is an updatable structure containing information or data about a dynamic component, where the information can change over time. Anytime the data inside these components are changed, State re-render the app to reflect these changes. Generally, these changes in data happen due to user-triggered events on the frontend. State can be considered the heart of React components as it determines the component’s behavior and its rendering method. It can also be thought of as representing the component’s local State or information. State can be accessed or modified only on the inside or directly by component.
import React, { Component } from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { displayBio: true };
}
render() {
const bio = this.state.displayBio ? (
<div>
<p><h3>Aglowid is a leading React.js development company</h3></p>
</div>
) : null;
return (
<div>
<h1> Welcome to Aglowid! </h1>
{ bio }
</div>
);
}
}
export default App;
For setting the State, it is needed to call the super()
method in the constructor. This is because of this. The State doesn’t get initialized before calling the super()
method.
State is different from props as the value of the component state can be changed. We can use setState()
method and pass a new state object as an argument. According to React.js official docs, When we change the value of a State object, the component re-renders after which the output gets updated with the new values.
class bike extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "Harley Davidson",
model: "Street Glide",
color: "red",
year: 2022,
};
}
changeColor = () => {
this.setState({ color: "black" });
};
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
<button type="button" onClick={this.changeColor}>
Change color
</button>
</div>
);
}
}
Components are the core of React development. In React, there is two kind of components – stateful and stateless. As the name suggests, stateful are components that hold some state, whereas Stateless are components with no state. Both these components can make use of props. To understand the differences between Stateful and Stateless components, we need to understand them individually:
var React = require("react");
var Header = React.createClass({
getInitialState: function () {
return {
someVariable: "I remember something",
};
},
render: function () {
return <img src={"mypicture.png"} />;
},
});
module.exports = Header;
Stateful components may or may not include props but definitely will have State. They have their State that can be changed at any time. Whenever the component changes State, it will re-render to reflect the React web app changes. Such components are helpful when your apps need to respond to user interactions and inputs. This enables React apps to have a dynamic UI with the help of client-server communication, allowing React developers to create dynamic and interactive React pages.
When to use Stateful Components
React Stateless Components
var React = require("react");
var Header = React.createClass({
getInitialState: function () {
return {
someVariable: "I remember something",
};
},
render: function () {
return <img src={"mypicture.png"} />;
},
});
module.exports = Header;
Stateless components can be created using function or class. However, most developers prefer going for stateless functional components as they are easier to understand, write and test. Stateless components are similar to a function that takes an input (such as props) and returns the output (React element). Such components are useful when the developer wants to represent the props and doesn’t need the components to be interactive. In addition, these components are easier to understand and taste than stateful components.
When to use Stateless Components
State generally could only be used in class components earlier and not functional components. This is also a reason that functional components were considered to be stateless components. Although after React hooks got introduced, State became available for use in class and functional components. However, that creates a dependency, and you can only use State if your project uses React hooks.
So far, we have grasped the concepts of React props and State in detail and understood the differences between stateful and stateless components of React. We can now make a quick comparison highlighting the differences between React props and State:
Props can be empty, although State need an initial value
Props don’t need to have any set initial value. State, however, need to have an initial value. For stateful components, the first value of State needs to be declared directly:
You can use constructor()
: for class components
class CalmDown extends React.Component {
constructor(props) {
super(props);
this.state = {
currentState: "not-panic",
};
}
}
For functional components, we can set the initial value using React Hook useState()
:
import { useState } from "react";
function TimeToPanic() {
// Declare a new state variable, which we'll call "mood"
const [mood, changeMood] = useState("calm"); // we declare a new state variable “mood” with the initial value equal to 0
return (
<div>
<p>You feel {mood}</p>
<button onClick={() => changeMood((mood = "the panic"))}>Click me</button>
</div>
);
}
Here changeMood is a method for developers to update the mood’s state. This component can get the initial state from the parent component. For props we can pass an empty value since they don’t need an initial value.
function CatComponent(props) {
return (
<div>
{props.catName} Cat, Eye Color: {props.eyeColor}, Age: {props.age}
</div>
);
}
CatComponent.defaultProps = {
catName: "Sandy",
eyeColor: "deep blue",
age: "120",
};
const cat = <CatComponent catName="Milk" />;
Here, CatComponent renders all the following strings – “Milk Cat, Eye Color: deep blue, Age: 120”. Here we passed empty values for props attributes eyeColor and age; the component falls back to the default values. The attribute named catName returns the previously assigned value. If we call the CatComponent without default values, it will render “Milk Cat, Eye Color, Age:”
A major limitation to props is that they are immutable. As discussed earlier, Props are read-only elements for which a component cannot set a new value. React has pure components that don’t alter their inputs or outputs and always display the same result for the same props. If you try changing the value of a prop, it will throw back a TypeError, and that code won’t work:
function Add(props) {
if (typeof props.n2 === 'undefined') {
props.n2 = 0
}
return (
<div>
{props.n1} + {props.n2} = {props.n1 + props.n2}
</div>
)
} // TypeError: Cannot add property n2, object is not extensible
Props are meant to only pass information from one component to the other. Components can’t change their props, but they are still responsible for the props of their child components in the component tree.
State, on the other hand, React state are mutable. Stateful components change each time user makes any form of interaction with the app. Also, state components are responsible only for managing their State and have no influence on the child components. Each stateful component is private.
Now that we understand the basic differences between React state vs Props, we should also understand their use cases and where using props is better suited than state and vice versa:
Wrapping up!
These are all the essential differences between React Props and the State you need to know to use React components efficiently in your next React project. Make sure to understand the nature, purpose, possibilities, and limitations of both and use them to best suit your specific requirements.
Also Published Here