What is The Difference Between State and Props in React?

What is the difference between State and Props in React? — Flatlogic Blog

Props and state definition

import React, { Component } from ‘react’;

class App extends Component {
render() {
const greeting = ‘Welcome to React’;

return (
<div>
<Greeting greeting={greeting} />
</div>
);
}
}

class Greeting extends Component {
render() {
return <h1>{this.props.greeting}</h1>;
}
}

export default App;
import React, { Component } from 'react';

class App extends Component {
render() {
const greeting = 'Welcome to React';

return (
<div>
<Greeting greeting={greeting} />
</div>
);
}
}

const Greeting = props => <h1>{props.greeting}</h1>; // here an arrow function receives props with the name greetings

export default App;

State

import React, { Component } from 'react';

class Button extends Component {
constructor(props) {
super(props);
this.state = { counter: 1 };
}
render() {
return (
<button>{this.state.counter}</button>
);
}
}
export default Button;
import React from 'react';

function Counter() {
const [count, setCount] = React.useState(1);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

export default Counter;

Stateful and stateless components

Brief comparison

  • React components re-render if props or state have changed. Any update from anywhere in the code triggers an automatic re-render of the appropriate part of the User Interface.
  • Props and state are JS objects, which means they both contain as many properties and methods as we need.
  • The same combination of props and state must produce the same output. This type of component is deterministic.
State and Props in React: key differences

State vs. props — detailed comparison

State has to have the initial value, while props can be empty

class CalmDown extends React.Component {
constructor(props) {
super(props);

this.state = {
currentState: "not-panic",
}
}
}
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>
);
}
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"/>

Props are immutable, while state is mutable

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
  • No direct modification: command this.state.name = ‘me’; is allowed only for the initial initialization of state, in render() method we need to use setState()
  • State updates may be asynchronous: setState() callbacks all happen together at the end of the state update phase in React, not immediately after that particular update happens. That may lead to confusion.

The role state and props play

The role of state:

  • Make the components interactive
  • Provide users with an opportunity to modify the state
  • Track data values over the lifetime of the component
  • Update the UI when the state has been changed
  • React when the time passes (interval or timeout)

The role of props:

  • To display static non-interactive components and data
  • To pass data from a component to component

State can be passed as props to child components

class CalmDown extends React.Component {
constructor(props) {
super(props);

this.state = {
currentState: "do not panic",
}
}
render() {
return <div>Just remember: {this.state.currentState}</div>;
<MyChild mood = {this.state.currentState}/>
}
}
class MyChild extends React.Component {
return <h1>Hello! I {this.props.mood}</h1>;
}
}
}
this.setState({ currentState: ‘PANIC!’})
MyChild mood ={this.state.currentState} onNameChanged={this.handleMood} />
handleMood: function(newMood) {
this.setState({ currentState: newMood });
}

Usage of state and props in higher-order components

import React from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

class Example extends React.Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
};

constructor(props) {
super(props);

this.state = {
email: 'admin@flatlogic.com',
password: 'password',
};

this.doLogin = this.doLogin.bind(this);
}

doLogin(e) {
e.preventDefault();
this.props.dispatch(loginUser({ email: this.state.email, password: this.state.password }));
}

isLogin () {
return this.props.isAuthenticated
}

render() {
return (
<form onSubmit={this.doLogin}>
<button type="submit">Login</button>
</form>
);
}
}

function mapStateToProps(state) {
return {
isAuthenticated: state.auth.isAuthenticated,
};
}

export default withRouter(connect(mapStateToProps)(Login));
functional components:
import React from "react";
import { useDispatch, useSelector } from "react-redux";

const Login = () => {
const dispatch = useDispatch(); const isAuth = useSelector(store => store.auth.isAuth)


const doLogin = () => {
if (isAuth) {
// some async logic
}
}

return (
<form onSubmit={() => dispatch(doLogin())}>
<button type="submit">Login</button>
</form>
);
};

export default Login;

So when to use state and props?

Some basic rules:

  1. Components without state are preferable. State increases the common complexity of the app, makes the render result less predictable and testing less steady. Although you can’t avoid using state in the app because state is the basis for building interactive apps in React, just make sure that your app has as many Stateful components as possible.
  2. A wide-spread pattern of building apps is to make several stateful components on top of the hierarchy and create stateless components under them, passing all necessary information and staff via props from parents to child components. The point here is to isolate the logic of interaction on the top of the app in parent stateful components and to transfer the responsibility of rendering data to child stateless components. ####When we should use stateless components:
  3. When we need to display the data
  4. When we build a non-interactive element in the UI
  5. When we have a stateful component above, we should check whether it’s possible to use state from above rather than introduce a new local state ####When we should use stateful components:
  6. When the component is supposed to accept user input
  7. When we build an interactive UI element
  8. When the component needs to work with data that it can’t get as props from parent components
  9. When we work with fetching data

You might also like these articles:

--

--

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