React Props vs State

_ 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:

What are Props in React?

Props in React

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.

Properties in React components

_ Also Read: Latest React 18 Features & Changes_

Let us understand how props work step by step:

1. Sending props to a component

Adding a “brand” attribute to the Bike element:

const myelement = <Bike brand="Harley Davidson" />;

Enter fullscreen mode Exit fullscreen mode

2. The component will receive the argument as a props object

Add the brand attribute in the component:

function Bike(props) {

return <h2> I am a { props.brand } !</h2>;

}

Enter fullscreen mode Exit fullscreen mode

3.1 Passing data as a string from one component to another

Pass the “brand” property from the Garage component to the Car 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"));

Enter fullscreen mode Exit fullscreen mode

3.2 Passing a variable from one component to another

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"));

Enter fullscreen mode Exit fullscreen mode

3.3 Passing an Object from one component to another

Create an Object named carInfo and send it to the Car 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={carInfo} />
    </>
  );
}

ReactDOM.render(<Garage />, document.getElementById("root"));

Enter fullscreen mode Exit fullscreen mode

What are State in React?

State in React

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.

State in React components

React State Code Example

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;

Enter fullscreen mode Exit fullscreen mode

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.

_ Also Read: How to Secure ReactJS App?_

Changing State in React.js

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 Car 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>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Stateful Component vs Stateless Component in React

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:

LookinG for React developers to hire?
Get in touch to develop highly scalable web app project.
HIRE REACTJS DEVELOPERS

React Stateful 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;

Enter fullscreen mode Exit fullscreen mode

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.

_ Also Read: ReactJs Advantages and Disadvantages_

When to use Stateful Components

  1. When you need to build elements that accept user input like click, press, and more
  2. When you need to build interactive elements on your page
  3. When you need to pass data that can’t be passed down as props
  4. When the data is dependent on State for rendering

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;

Enter fullscreen mode Exit fullscreen mode

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

  1. When you only need to present the props
  2. When creating static elements that don’t need to be interactive
  3. When there is no requirement of State or internal variables
  4. When you need reusable code

Can I use State in all 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.

Understanding the differences: React State vs Props

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 :

Differences Props State
Component Data Behaviour Receives data from outside with props Create and manage data within state
Data Role To pass data between different components To manage data within components
Data Accessibility Data from props is read-only, cannot be modified Data can be modified within component but cannot be accessed from outside
Initial Value Requirement Passed from parent component, can be empty Needs an initial value, can get initial value from parent component
Permissions Read only Read and write
Component Type Static , Non-Interactive Dynamic, Interactive
Mutability Immutable Mutable
Stateless components Cant have props Can’t have 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",
    };
  }
}

Enter fullscreen mode Exit fullscreen mode

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>
  );
}

Enter fullscreen mode Exit fullscreen mode

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" />;

Enter fullscreen mode Exit fullscreen mode

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:”

_ Also Read: – React SEO Guide_

React State vs Props – Mutability

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

Enter fullscreen mode Exit fullscreen mode

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.

React State vs Props – Use Cases

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:

When to use Props

  • When you want to display non-interactive components and data
  • For passing data from one component to another

When to use State

  • For making components interactive
  • Track changing data values of components for their lifetime
  • Update the frontend when state changes
  • Enable users to modify the State – for instance, interact with a contact form or buttons

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.

Do you have a unique app Idea? & you’re Looking to Hire a Developer?

Hire Certified Developers To Build Robust Feature, Rich App And Websites At An Affordable Price

HIRE DEVELOPERS