What is the difference between state and props in React?

What is the difference between state and props in React?

I was watching a Pluralsight course on React and the instructor stated that props should not be changed. I’m now reading an article (uberVU/react-guide) on props vs. state and it says

Both props and state changes trigger a render update.

Later in the article it says:

Props (short for properties) are a Component’s configuration, its options if you may. They are received from above and immutable.

So props can change but they should be immutable?
When should you use props and when should you use state?
If you have data that a React component needs, should it be passed through props or setup in the React component via getInitialState?

Solutions/Answers:

Solution 1:

Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child within the render method of the parent as the second argument to React.createElement() or, if you’re using JSX, the more familiar tag attributes.

<MyChild name={this.state.childsName} />

The parent’s state value of childsName becomes the child’s this.props.name. From the child’s perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:

this.setState({ childsName: 'New name' });

and React will propagate it to the child for you. A natural follow-on question is: what if the child needs to change its name prop? This is usually done through child events and parent callbacks. The child might expose an event called, for example, onNameChanged. The parent would then subscribe to the event by passing a callback handler.

<MyChild name={this.state.childsName} onNameChanged={this.handleName} />

The child would pass its requested new name as an argument to the event callback by calling, e.g., this.props.onNameChanged('New name'), and the parent would use the name in the event handler to update its state.

handleName: function(newName) {
   this.setState({ childsName: newName });
}

Solution 2:

For parent-child communication, simply pass props.

Use state to store the data your current page needs in your controller-view.

Use props to pass data & event handlers down to your child components.

These lists should help guide you when working with data in your components.

Props

  • are immutable
    • which lets React do fast reference checks
  • are used to pass data down from your view-controller
    • your top level component
  • have better performance
    • use this to pass data to child components

State

  • should be managed in your view-controller
    • your top level component
  • is mutable
  • has worse performance
  • should not be accessed from child components
    • pass it down with props instead

For communication between two components that don’t have a
parent-child relationship, you can set up your own global event
system. Subscribe to events in componentDidMount(), unsubscribe in
componentWillUnmount(), and call setState() when you receive an event.
Flux pattern is one of the possible ways to arrange this.
https://facebook.github.io/react/tips/communicate-between-components.html

What Components Should Have State?

Most of your components should simply take some data from props and
render it. However, sometimes you need to respond to user input, a
server request or the passage of time. For this you use state.

Try to keep as many of your components as possible stateless. By doing
this you’ll isolate the state to its most logical place and minimize
redundancy, making it easier to reason about your application.

A common pattern is to create several stateless components that just
render data, and have a stateful component above them in the hierarchy
that passes its state to its children via props. The stateful
component encapsulates all of the interaction logic, while the
stateless components take care of rendering data in a declarative way.
https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-components-should-have-state

What Should Go in State?

State should contain data that a component’s event handlers may change
to trigger a UI update. In real apps this data tends to be very small
and JSON-serializable. When building a stateful component, think about
the minimal possible representation of its state, and only store those
properties in this.state. Inside of render() simply compute any other
information you need based on this state. You’ll find that thinking
about and writing applications in this way tends to lead to the most
correct application, since adding redundant or computed values to
state means that you need to explicitly keep them in sync rather than
rely on React computing them for you.
https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-should-go-in-state

Solution 3:

The props vs state summary I like best is here: https://github.com/uberVU/react-guide/blob/master/props-vs-state.md Big hat tip to those guys. Below is an edited version of that page:


props vs state

tl;dr If a Component needs to alter one of its attributes at some point in time, that attribute should be part of its state, otherwise it should just be a prop for that Component.


props

Props (short for properties) are a Component’s configuration. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data — callback functions may be passed in as props.

state

The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.

A Component manages its own state internally. Besides setting an initial state, it has no business fiddling with the state of its children. You might conceptualize state as private to that component.

Changing props and state

                                                   props   state
    Can get initial value from parent Component?    Yes     Yes
    Can be changed by parent Component?             Yes     No
    Can set default values inside Component?*       Yes     Yes
    Can change inside Component?                    No      Yes
    Can set initial value for child Components?     Yes     Yes
    Can change in child Components?                 Yes     No
  • Note that both props and state initial values received from parents override default values defined inside a Component.

Should this Component have state?

State is optional. Since state increases complexity and reduces predictability, a Component without state is preferable. Even though you clearly can’t do without state in an interactive app, you should avoid having too many Stateful Components.

Component types

Stateless Component Only props, no state. There’s not much going on besides the render() function. Their logic revolves around the props they receive. This makes them very easy to follow, and to test.

Stateful Component Both props and state. These are used when your component must retain some state. This is a good place for client-server communication (XHR, web sockets, etc.), processing data and responding to user events. These sort of logistics should be encapsulated in a moderate number of Stateful Components, while all visualization and formatting logic should move downstream into many Stateless Components.

sources

Solution 4:

Most of the answers are confusing Beginners rather clarifying. It’s very hard to
relate and understand. You can understand it by relating it to Plain
JS.

In simple words,

State is referred to the local state of the component which cannot be accessed and modified outside of the component and only can be used & modified inside the component.

Plain JS

const DummyFunction = () => {
  let name = 'Manoj';
  console.log(`Hey ${name}`)
}

React JS Equivalent

class DummyComponent extends React.Component {
  state = {
    name: 'Manoj'
  }
  render() {
    return <div>Hello {this.state.name}</div>;
  }

Props, on the other hand,make components reusable by giving components the ability to receive data from the parent component in the form of props.

Plain JS

const DummyFunction = (name) => {
  console.log(`Hey ${name}`)
}
DummyFunction('Manoj');
DummyFunction('Ajay');

React JS

class DummyComponent extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }

}
// when using the component
<DummyComponent name="Manoj" />
<DummyComponent name="Ajay" />

Credits: https://medium.com/@manojsinghnegi

Article Linke:https://medium.com/@manojsinghnegi/react-state-vs-props-explained-51beebd73b21

Solution 5:

props (short for “properties”) and state are both plain JavaScript
objects. While both hold information that influences the output of
render, they are different in one important way: props get passed to
the component (similar to function parameters) whereas state is
managed within the component (similar to variables declared within a
function).

So simply state is limited to your current component but props can be pass to any component you wish… You can pass the state of the current component as prop to other components…

Also in React, we have stateless components which only have props and not internal state…

The example below showing how they work in your app:

Parent (state-full component):

class SuperClock extends React.Component {

  constructor(props) {
    super(props);
    this.state = {name: "Alireza", date: new Date().toLocaleTimeString()};
  }

  render() {
    return (
      <div>
        <Clock name={this.state.name} date={this.state.date} />
      </div>
    );
  }
}

Child (state-less component):

const Clock = ({name}, {date}) => (
    <div>
      <h1>{`Hi ${name}`}.</h1>
      <h2>{`It is ${date}`}.</h2>
    </div>
);

Solution 6:

The key difference between props and state is that state is internal and controlled by the component itself while props are external and controlled by whatever renders the component.

function A(props) {
  return <h1>{props.message}</h1>
}

render(<A message=”hello” />,document.getElementById(“root”));


class A extends React.Component{  
  constructor(props) {  
    super(props)  
    this.state={data:"Sample Data"}  
  }  
  render() {
    return(<h2>Class State data: {this.state.data}</h2>)  
  } 
}

render(<A />, document.getElementById("root"));

State VS Props

  • State can be changed (Mutable)
  • Whereas Props can’t (Immutable)