Menu

What is the difference between props and state?

RohitMCN 2 years ago 0 41

In this article, we will learn about props and state. How do these work in ReactJS?

What are props?

Props are a Component’s attributes in React that are useful for customization. Since a prop modifies a component’s behavior or output, it can be compared to a parameter.

Syntax of Props in React JS

class ParentComponent extends Component {    
    render() {    
        return (        
            <ChildComponent name="First Child" />    
        );  
    }
}

const ChildComponent = (props) => {    
    return <p>{props.name}</p>; 
};

With props, how do you pass data?

Here is a sample of some data passing using props:

class ParentComponent extends Component {    
    render() {    
        return (        
            <ChildComponent name="First Child" />    
        );  
    }
}

const ChildComponent = (props) => {    
    return <p>{props.name}</p>; 
};

First, we must define or obtain some information from the parent component, then we must give it to the “prop” attribute of a child component.

<ChildComponent name="First Child" />

Here, “Name” is a defined prop that holds text information. After that, we can pass data using props to functions as if they were arguments:

const ChildComponent = (props) => {  
  // statements
};

Finally, we retrieve the prop data and render it using dot notation:

return <p>{props.name}</p>;

How to use props in ReactJS?

Props are another method for transferring data between components as parameters.

function Mobile(props) {
  return <h2>I am a { props.brand }!</h2>;
}

function Store() {
  const MobileName = "One plus";
  return (
    <>
      <h1>Who lives in my Mobile Store?</h1>
      <Mobile brand={ MobileName } />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Store />);

export default Store;

In the above code, we are getting the element details using the getElementById, which is further linked to the “Store” function using the render(). Store() has a demo template that eventually uses a prop to show the output as “I am a One Plus!”.

Note

We are using {} so as to pass the value from Store() to Mobile(). And then we used {} to print the value of the prop.brand. Not using {} will not print the value. It will print the element ID.

Output

What is the state?

A built-in React object called the state is used to store data or details about the component. A component may change over time, and a new rendering of the component is produced each time it happens. The component’s behavior and rendering are determined by changes in state, which may occur in reaction to user input or system-generated events.

Syntax of State in React JS

class Test extends React.Component {    
    constructor() {    
        this.state = {      
            id: 1,      
            name: "test"    
        };  
    }    
    
    render() {    
        return (      
            <div>        
              <p>{this.state.id}</p>        
              <p>{this.state.name}</p>      
            </div>    
        );  
    }
}

How to use state in ReactJS?

The state object is initialized in the constructor:

class Mobile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "One Plus",
      model: "Nord 2",
      color: "red ",
    };
  }
  changeColor = () => {
    this.setState({color: "blue "});
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
        </p>
        <button
          type="button"
          onClick={this.changeColor}
        >Change color</button>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Mobile />);

export default Mobile;

In the above code, we are getting the element details using the getElementById, which is further linked to the “Mobile” function using the render(). We are using this.state.brand and this.state.color for passing the data. We are creating a button to change the color. When we click on the button “Change color”, the Color will change automatically.

Output

Now, Click on the “Change color” box, Color will be changed:

What are the differences between props and state?

The difference is which component is the data’s owner. Locally owned and updated state is controlled by the component itself. Props are read-only and owned by a parent component. Only when a callback function is passed to the child to cause an upstream change can props be changed.

A prop can be used to transfer a parent component’s state to a child component. Although they both refer to the same variable, only the parent component is able to make changes.

Let’s review and examine the key distinctions between props and state:

  • While the state allows components to create and maintain their own data, props allow them to receive data from the outside.
  • Data is passed using props, whereas the state is used to manage data.
  • A component that receives read-only data from props cannot modify it once it has received it from the outside.
  • State data is private but can be altered by its own component (cannot be accessed from outside).
  • Only parent components can pass props on to their children (unidirectional flow).
  • SetState () method should be used to modify the state.

Comparative advantages of React and Props

 There are some similarities between Props and React, including:

  1. Using this results in both being read-only.
  2. Both are just JS objects.
  3. Both can have default values

Conclusion

Understanding React state and props may appear difficult and a little confused. However, knowing it is the proper order might make it easier for you to follow. A component’s state is an object that holds both private and public local data. Additionally, it can be applied to modify a component’s output. Props are simply input definitions that tell you what to want to see.

Thank you for reading the article. I hope it will help you to learn about state and props in ReactJS.

– Advertisement – BuzzMag Ad
Written By

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *