State vs props explained
The concept of state and props can be confusing when you first start out in React, they sound pretty similar: they’re both basically variables right? That’s true, but they’re used in fundamentally different ways.
Props
Props are basically function parameters
Like regular functions, React components are designed to be used over and over again with different data. That data is passed in from the outside via a prop.
If you’re using JSX, you pass props exactly the same as you would an HTML attribute.
<Lorem prop="lorem" />
// When a prop is boolean, it doesn't require a value
<Lorem otherProp />
Props are immutable
The key thing about props is that they can’t change during the lifecycle of the component. Again this is the same as a regular function, you don’t change the data of a function parameter either.
The parent can change them though, when this happens the component will re-render and kick off another lifecycle.
Any component that uses props but not state is considered to be ‘pure’, if you give it the same input (props) it will return the same output. When developing in React the majority of your components are likely to be pure.
Props come from the parent, except when they don’t
Props are passed into a component from above, but you can also set default props. This means if you don’t specifically pass the prop, it still has a value you can use in the component.
In practice, any prop that is not mandatory should have a default prop value.
// Ipsum can be used as props.ipsum
Lorem.defaultProps = {
ipsum: 3,
};
State
State is internal
State is created and maintained inside the component, you can’t access or change it from outside. It’s basically the same as a scoped variable.
Initially it’s set inside the component constructor
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
}
}
}
You can (and should) change state
Unlike props, the state is supposed to be changed, if a state value never needs to change then it should be a prop.
But: you should never change it directly, always use setState
this.setState({
loading: false,
});
Since changing the state also causes the component to re-render, you’ll need to be careful where you change it. If you change it inside render then you’ll get an infinite loop.