State vs. Props
props do share some common ground:
- Both are plain JS objects
- Both can have default values
- Both should be accessed/read via
this.state, but neither should be given values this way. I.e., both are readonly when using
However they are used for different reasons and in different ways.
- Props are passed into a component from above. Either a parent component or from the starting scope where React is originally rendered.
- Props are intended as configuration values passed into the component. Think of them like arguments passed into a function (If you don't use JSX that is exactly what they are).
- Props are immutable to the component receiving them. I.e., don't change props passed to a component from within the component
- State is a serializable representation of data (a JS object) at one point in time that typically is tied to UI
- State should always start with a default value and then the state is mutated internally by the component using
- State can only be mutated by the component that contains the state, it is private in this sense.
- Don't mutate the state of child components. A component should never have shared mutable state.
- State should only contain the minimal amount of data needed to represent your UI's state, it should not contain computed data, other React components, or duplicated data from props.
- State should be avoided if at all possible. I.e., stateless components are ideal, stateful components add complexity. The React documentation suggest: "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."