React props vs state

Chanchala Gorale
1 min readAug 19, 2021
  • 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} /></>);}

--

--