What is the difference between props and state in React?

When working with React, one issue that came up was: What is the difference between props and state? But before we get into their differences. Let’s take a look at what they have in common: Props and state are both simple javascript objects. That store’s information that impacts a component’s render output.

Props are pass down from the parent component to its children, whereas the state is produce and maintained inside the component. As a result, props are immutable and should only be pass down, not modified. State, on the other hand, is dynamic and internal to the component, thus it isn’t pass on to children.

Props

Because props cannot be change throughout the lifecycle of a component, they should be utilize when dealing with data that does not need to be act on or updated. These components are known as “pure” or “stateless” components.

State

The state should be utilize to manage changes inside a component. A stateful component gives the initial or default state when it initially mounts. This default state will change and be re-rendere based on user activities.

setState() for Props and State

A state may be change with the setState() function. It’s worth noting that setState() is asynchronous, thus it should be provided a function rather than an object. setState() will always be provided the most recent version of a state as a result of this.

Here’s a sample from the official reactjs documentation:

Because setState() is provided an object, the following code will not operate as expects.

incrementCount() {
  this.setState({count: this.state.count + 1});
}

Instead, the above will be written like this:

incrementCount() {
  this.setState((state) => {
    return {count: state.count + 1}
  });
}

The incrementCount() updater will operate on the current state and be able to chain its updates since a function has been pass. Previously, when using this.state, the updates would always use the default state value, which was not the expected behavior.

Summary of Props and State

To review, Props are immutable values that are pass down from parent to child components. During the lifecycle of a component, props cannot be modifies.

A component’s state is manage within it and is “private” to that component. It starts with a default value that varies over time in response to human input.

If you want to know more about React then please visit react official documentation.

That’s all for this article if you have any queries please contact us through our website or email us at [email protected]m

Leave a Comment