Difference between State & Props

moazamdev

Moazam Ali

Posted on October 23, 2022

Difference between State & Props

Have you ever wondered how we can use the data of one component in other components in React JS? To use the data of the parent component in its child component we use props and to store data we use state in the parent component.

In this article, we will learn the difference between state and props with some examples.

 

State

React State is used to store data in your top-level component i.e. parent component. It is a local data storage that is local to the component only. The State is mutable which means it can be modified and Each component can have its state. The state is both read and write.

The State can not be accessed and modified outside of the component. You can think of state as local variables in a function that are not accessed outside the function block. For example,

import React from "react";

class Colors extends React.Component {
 state = {
   code: "#323232"
 };

 render() {
   return <h2>Color Code: {this.state.code}</h2>;
 }
}
export default Colors;

// Output: Color Code: #323232 
Enter fullscreen mode Exit fullscreen mode

 

Props

React Props also known as properties, are used to pass data down to the child components from top level components (parent components). Props are immutable which means that it cannot be modified and are read-only.

Child components receive data from their parent components in the form of props. You can think of props as function parameters. For example

import React from "react";

// creating Colors functional component
const Colors = (props) => {
 return <h2>Color Code: {props.code}</h2>;
};

class App extends React.Component {
 state = {
   code: "#323232"
 };
 render() {
   // passing state as a prop to Colors component
   return <Colors code={this.state.code} />;
 }
}
export default App;

// Output: Color Code: #323232
Enter fullscreen mode Exit fullscreen mode

 

Wrapping up!

  • State is a local storage for the component which cannot be accessed outside of the component.
  • Props are used to pass data down to the child components from parent components.

That's all for this article, thanks for reading. Catch you later.

💻 Happy Coding


💖 💪 🙅 🚩
moazamdev
Moazam Ali

Posted on October 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related