How to manage a state in React
Every React component can have a state associated with them. This state is an object which stores the property values and attributes that belong to a component.
The state is able to keep data from different components in-sync because each state update re-renders all relevant components.
React provides two main built-in methods to maintain state:
useStatehook for functional componentssetStatemethod for class components
We will go over both these methods in detail.
Managing state using useState hook
We can use the useState hook to maintain the state of our functional component. It returns a variable and a function which can later be used to change the value of that variable.
Example
import React from 'react';
import ReactDOM from 'react-dom/client';
import {useState} from 'react';
function App(){
const [fullname, setFullname] = useState("");
const handleName = (e) => {setFullname(e.target.value);}
return (
<div>
<label htmlFor="fullname"> Full Name: </label>
<input type="text" name="fullname" onChange={(e)=>{handleName(e)}} />
<div>
<h4> Greetings, {fullname}!</h4>
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Explanation
The explanation of the code above is as follows:
Line 3: Imports the
useStatefunction from thereactlibrary.Line 7: This line uses the
useStatehook to create a state variablefullnameand this hook also returns a functionsetFullnamewhich will later be used to updatefullname.Line 9: Declaring a function
handleNamewhich uses thesetFullnamefunction to update the value offullnamewith the value that is entered by the user in the input field.Line 14: Uses the
onChangeattribute of the theinputfield and calls thehandleNamefunction when it detects a change in the input field. It sends an object to thehandleNamefunction which contains the updated value that was entered by the user.
Managing state using setState method
We can store the state of a class component in a variable/attribute named state. The state variable/attribute of a class component is assigned a JavaScript object which is the state of this component.
Whenever we want to change the state of this component we can either change it directly by this.state.stateVaraibleName = newValue .It is, however, not recommended because this will only change the value of that state variable but not render it on screen.
If we want to render that update on the screen then we should change the state using the setState method. It automatically re-renders the entire component with updated values.
Example
import React from 'react';
import ReactDOM from 'react-dom';
export default class App extends React.Component {
state = {fullname: ""};
stateChange = (f) => {
const {name, value} = f.target;
this.setState({[name]: value,});
}
render() {
return (
<div>
<label htmlFor="fullname"> Full Name: </label>
<input type="text" name="fullname" onChange={this.stateChange} />
<div>
<h4> Greetings, {this.state.fullname}!</h4>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
Explanation
The explanation of the code above is as follows:
Line 6: Defines the state of the class component.
Lines 8–11: Defines a function
stateChangewhich is called everytime a change is detected in the text box on screen.Line 10: This line calls the
setStatefunction and passes it a Javascript object with the updated value of the variable.
Line 17: Whenever a change is detected in the
inputfield, it calls thestateChangefunction.
Free Resources