STATE VS PROPS
props
(short for “properties”) and state
are both plain JavaScript objects.
While props
and state
both hold information relating to the component, they are used differently and should be kept separate.
props
contains information set by the parent component (although defaults can be set) and should not be changed.
state
contains “private” information for the component to initialise, change, and use on it’s own.
… props are a way of passing data from parent to child. … State is reserved only for interactivity, that is, data that changes over time.
props
get passed to the component (similar to function parameters) whereas state
is managed within the component (similar to variables declared within a function).
OK, so props “come from above.”
A component can also have default props, so if a prop isn’t passed through it can still be set.
Props should never be changed in a child component
class Welcome extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}
Welcome.defaultProps = {
name: "world",
};
State
class Button extends React.Component {
constructor() {
super();
this.state = {
count: 0,
};
}
updateCount() {
this.setState((prevState, props) => {
return { count: prevState.count + 1 }
});
}
render() {
return (<button
onClick={() => this.updateCount()}
>
Clicked {this.state.count} times
</button>);
}
}
state
is created in the component
constructor() {
super();
this.state = {
count: 0,
};
}
This is where state
gets it’s initial data. The inital data can be hard coded (as above), but it can also come from props
.
state
is changeable
updateCount() {
this.setState((prevState, props) => {
return { count: prevState.count + 1 }
});
}
setState
warning one!
It is tempting to write this.state.count = this.state.count + 1
. Do not do this! React cannot listen to the state getting updated in this way, so your component will not re-render. Always use setState
.
this.state
should not be assigned directly. Use this.setState
, instead.
this.setState
cannot be used in render
.