state
state can be used in both component base and functional base class with different methods.
Component-based Object
state is a special variable that represent the state of a Component
. Any class that extends Component from 'react' can have this. Usually the state variable contains a map of variables. React will monitor it, and if it is changed, the view using the variables in state will also be updated.
Here is an example that when the button is clicked, the state of the App component will be updated. Note that we need to use the method this.setState()
to update the state variable, so that the part that using this state, such as the UI binded with {} will be updated. Editing this.state directly and react will not update the UI binded with the edited state!
. The setState method will only update the related variables, and leave the already defined variable remain unchanged.
import React, { Component } from 'react'; import './App.css'; import Person from './Person/Person'; class App extends Component { state = { persons: [ { name: "Abc", age: "11" }, { name: "Def", age: "22" }, { name: "Ghi", age: "33" }, ], somethingElse: "somethingElse" } onButtonClicked = () => { this.setState({ persons: [ { name: "WTF?!", age: "11" }, { name: "Def", age: "22" }, { name: "Ghi", age: "33" }, ] }) console.log("clicked"); } render() { return ( <div className="App"> <button onClick={this.onButtonClicked}>Click</button> <h1>Reacsst!</h1> <Person name={this.state.persons[0].name} age={this.state.persons[0].age}>This is a demo</Person> </div > ) } } export default App;
When the button is clicked, the persons
in state will be updated, and the somethingElse
will remain unchanged.
To avoid race condition you might want to do something with the prevState
like:
onButtonClickHandler = () => { this.setState((prevState, props) => { return { catSound: "Meow Meow Meow" + " " + prevState.count, count: prevState.count + 1 } }); };
Functional-based Object
Use useState
. Unlike component-based state, we can have multiple hooks of useState. We can setup one like:
const [currentState, setStateHandler] = useState({ persons: [ { name: "Abc", age: "11" }, { name: "Def", age: "22" }, { name: "Ghi", age: "33" } ]});
To access it, use something like currentState.persons[0].name
. To set the state, do
import React, {useState} from "react"; . . . setStateHandler( persons: [ { name: "WTF?!", age: "11" }, { name: "Def", age: "22" }, { name: "Ghi", age: "33" } ]}) )
note that the state will be completely replaced instead of update like the one in component-based.