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:

  • useState hook for functional components

  • setState method 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 useState function from the react library.

  • Line 7: This line uses the useState hook to create a state variable fullname and this hook also returns a function setFullname which will later be used to update fullname.

  • Line 9: Declaring a function handleName which uses the setFullname function to update the value of fullname with the value that is entered by the user in the input field.

  • Line 14: Uses the onChange attribute of the the input field and calls the handleName function when it detects a change in the input field. It sends an object to the handleName function 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'));
Maintaining and updating state in class components.

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 stateChange which is called everytime a change is detected in the text box on screen.

    • Line 10: This line calls the setState function and passes it a Javascript object with the updated value of the variable.

  • Line 17: Whenever a change is detected in the input field, it calls the stateChange function.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved