In React, state is a plain JavaScript object that is used to Record & React to user events.
Functional components DO NOT have state.
Each class based component in React has its own state object.
Each instance of a class based component has it own copy of state.
Whenever a component's state is changed, the component immediately re-renders. And it also forces all of its children to re-render as well.
Before we use state inside of a component, we need to initialize the state object. To do this, we initialize the state to plain JS object inside of the class's constructor.
constructor(props) {
super(props);
this.state = { term: '' };
}
- All JS classes have a special function called as "constructor".
- The constructor function is the first and only function called automatically whenever a new instance of the class is created.
this.state = { term: '' }
is the code which will initialize the state object. Whenever we want to initialize state, we create a new object, and assign it tothis.state
. The object we assign also contains "properties" we want to record on state.
Only in the constructor, we make use of this.state = { term: '' }
. To update the state, we ALWAYS code:
this.setState({ term: event.target.value })
and we NEVER write:
this.state.term = event.target.value // BAD, BAD, BAD
So, what does below code do?
import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
}
render() {
return (
<div>
<input onChange = { event => (this.setState({ term: event.target.value}))} />
Value of State: {event.target.value}
</div>
);
}
}
export default SearchBar;
The below line:
<input onChange = { event => (this.setState({ term: event.target.value}))} />
works in below fashion:
- Whenever a word is typed in <input> text field,
- onChange event triggers the event handler code
event => (this.setState({ term: event.target.value})
Event handler assigns the input value to
this.state.term
As soon as the state is updated, it causes to re-render the component.
Here, the component "SearchBar" re-renders, and whatever is typed in <input> text field is displayed on screen.
Every time
this.setState()
s called, React updates the state, calculates a diff between the previous state and the new state, and injects a set of changes to the DOM on the page. This results a fast and efficient updates to your UI.