React State & Props
One of the many amazing features of React is its built in data management through the use State and of Props (properties). Its ability to save data in a parent or child component and to also pass said data to one another in such a friendly manner. Makes React such a critical part of any programmers arsenal.
So today I’d like to go into a brief overview of how State and Props work incase you’re needing a quick recap coming back from another language or just getting started; lets get into it!
State & Props :
— React controls the data flow in the components with state and props
— The data in states and props are used to render the Component with dynamic data
# Understanding ReactJS Props :
- In ReactJS props are equivalent to parameters of a pure javascript function.
- In ReactJS every component is treated as a pure javascript function.
- In ReactJS we use props to send data to components.
- One of the most important features of props is that they can be passed by a parent component to its child components
#Understanding ReactJS State :
— State is like a data store to the ReactJS component. It is mostly used to update the component when user performed some action like clicking button
, typing some text
, pressing some key
, etc.
— State is strictly belongs to a single Component
class Example extends Component{
constructor(props){
super(props);
this.state = {counter: 0}
}render(){
return(
<p>{this.state.counter}</p>
)
}
And can be changed later using inbuilt setState() function.
class Example extends Component{
constructor(props){
super(props);
this.state = {counter: 0}
this.increment = this.increment.bind(this);
}
increment(){
this.setState({counter: this.state.counter + 1})
}render(){
return(
<button onClick={this.increment}>Like</button>
<p>{this.state.counter}</p>
)
}
- Props are used to pass data from parent to child or by the component itself. They are immutable and thus will not be changed.
- State is used for mutable data, or data that will change. This is particularly useful for user input