One question that came up when working with React was: What's the difference between props
and state
? But before we explore their difference, let's look at their similarities: Props
and state
are both plain javascript objects, and they both hold information that affects the render output in a component.
The key difference between the two is that props
is passed down from the parent component to its children, whereas state
is created and managed within the component. Props
is therefore immutable, and should not be changed, only passed down. State
, on the other hand, is changeable, internal to the component, and is therefore not passed down to children components.
Props
Since props
cannot change during a component's lifecycle, they should be used when handling information that does not need to be acted on or edited. These components are known as "pure" or "stateless" components.
State
State
should therefore be used to handle changes internal to a component. When a stateful component first mounts, it is given an initial or default state. Based on user interactions, this default state will change and be re-rendered.
setState()
Using the setState()
method, state can be mutated. It is important to note that setState()
is asynchronous, and should therefore be passed a function instead of an object. This will ensure that setState()
is always passed the most recent version of state
.
Here is an example from the reactjs official documentation:
The below function will not work as intended, because setState()
is being passed an object.
incrementCount() {
this.setState({count: this.state.count + 1});
}
Instead, the above should be written like this:
incrementCount() {
this.setState((state) => {
return {count: state.count + 1}
});
}
Because a function is being passed, the incrementCount()
updater will act on the current state, and be able to chain its updates. Before, with this.state
the updates would act upon the default state value each time, which is not the desired action.
Summary
To review, Props
are immutable values that are passed down from parent components to their children. Props cannot be changed during a component's lifecycle.
State
is handled within a component and is "private" to that component. It starts with a default value that changes over time based on user interactions.
Top comments (0)