React props vs state

  • The purpose of the props is to pass the data, the purpose of the state is to manage the data
  • Props are received from outside- from the parent component, the state is created inside the current component
  • Props data is read-only and can only be passed from parent to child component, the state data can be created & modified within the component itself

Example: https://codesandbox.io/s/brave-neumann-1cxhc?file=/src/A.js

In class component:

//component Bclass B extends Component {render() {return (<>{/* accessing props */}<h3>This is props</h3><p>{this.props.fname} {this.props.lname}</p></>);}}//component Aclass A extends Component {constructor() {super();//state createdthis.state = {fname: "Chanchala",lname: "Gorale"}
}
render() {return (<>{/* Accessing state */}<h3>This is state</h3><p>{this.state.fname} {this.state.lname}</p>{/* passing props */}<B fname={this.state.fname} lname={this.state.lname} /></>);}}

In function component:

//component Bfunction B (props){return ( <>{/* accessing props */}<h3>This is props</h3><p>{props.fname} {props.lname}</p></>);}//component Afunction A() {const [state, setstate] = useState({fname: "Chanchala",lname: "Gorale"});return (<>{/* Accessing state  */}<h3>This is state</h3><p>{state.fname} {state.lname}</p>{/* passing props */}<B fname={state.fname} lname={state.lname} /></>);}

--

--

--

Technical Writer, Software Developer, Blogger, and Career Development Coach…

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

11 Frontend tricks that most Frontend Developers don’t know about

JS Modules and the story ahead:Part 2 (CommonJS,AMD,Harmony)

Event bus in NUXT

Truthy and Falsey — Assessing Javascript Booleans

Create a mobile app for your own token

Implementing Infinite Scrolling

Epic Games Store UI- MaterialUI, ReactJS, TypeScript — Handling the registration #10

Polls in RocketChat

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chanchala Gorale

Chanchala Gorale

Technical Writer, Software Developer, Blogger, and Career Development Coach…

More from Medium

Redux: React’s Single Source of Truth for State

Is React Good For SEO?

Passing State in React Router v6: The Bane of the Prop Jockey

A jockey on a horse. He really wants to win.

React Query: How to Memoize Results From useQueries Hook