React state meaning
State in React represents the components own local state.
The state cannot be accessed and modified outside the component
and can only be used inside the component.
Adding state to a component
Until recently when React Hooks were introduced there was no way of using state with function components. The new React Hooks feature will be discussed in a different post.
For now we will consider state in relation with using it inside class components.
Example using state inside class components
import React, { Component } from 'react';
class LoginBar extends Component{
constructor(props){
super(props);
this.state = {
userType: 'basic'
};
}
render(){
return(
Logged in as {this.props.username} type {this.state.userType}
);
}
}
export default LoginBar;
Initialise the state of a React component
There are 2 ways of initialising the state of a component:
- Inside the constructor
- Directly in the class as a class property
Initialise state inside the constructor
class LoginBar extends Component{
constructor(props){
super(props);
this.state = {
userType: 'basic'
};
}
render(){
return(
Logged in as {this.props.username} type {this.state.userType}
);
}
}
export default LoginBar;
Warning: Class components should always pass props to the base class constructor.
Directly in the class as a class property
import React, { Component } from 'react';
class LoginBar extends Component{
state = {
userType: 'basic'
};
render(){
return(
Logged in as {this.props.username} type {this.state.userType}
);
}
}
export default LoginBar;
For this to work we need to enable Babel’s class properties transform as the class property syntax is not yet in the official JS spec.
Both implementations achieve the same goal, just that the second one even though relying on a proposition is a little more clean.