Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Work with and Manipulate State in React ?

  • Last Updated : 24 Sep, 2021

Components in React provides the JSX (if you’re a beginner consider it a little bit similar to HTML), it can contain HTML tags and javascript expressions, ReactDOM somehow processes it and accordingly displays something on the frontend. Everything works fine until you only have to display static content, but what if your website is dynamic and you have to change something on the frontend, based on user interaction, In this case, you can use something like events and event handler to interact with the user or maybe several other internal things like dynamic adjustment, etc. But how would you go to tell ReactDOM that, display something based on some changes that occurred due to user interaction.

Approach: The way to re-render a component with ReactDOM is via a state change. It is a built-in object in react components it has some predefined functionalities and contains some information about the UI which is going to render on the frontend, also it controls the whole behavior of a component. We can make use of the state object to throw information on components so that ReactDOM can render something according to that information, basically, it is a dynamic data storage for components. We can also internally manage the state for different purposes, change in state forces react to call render function, and other lifecycle methods/ hooks in case of the functional component. 

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Creating react app and installing module: 

Step 1: Creating React Application



npx create-react-app state-demo

 

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd state-demo

Project Structure: It will look like the following.

 

Now first we will see how to create and manipulate state with class components.

1. Initializing state:

Syntax:

  • Initializing state object inside constructor
    constructor() {
        super();  // Don’t Forget to pass props if received
        this.state = {
            // Any object
        };
    }
  • Initializing state object using class property
    class MyComponent extends React.Component {
        state = {
            // any object
        };
    }

2. Accessing State: We can access state object anywhere in component with “this.state”, the state is local so, don’t try to access it from an outside component, if you need it outside then somehow you can pass it as props.



3. Manipulating State: Class component provides us a setState function we can call it anywhere in the component to manipulate state. 

  • Changing state object with a provided object as an argument while calling setState.
    this.setState({
        // anyobject
    });
  • When we have to update based on the previous state we pass a function that gets the previous state as a parameter.
    this.setState((prevState) => {
        // Do return a new state object 
        // after some manipulations 
    });
  • setState actions are asynchronous, so when we have to do something (ex- fetching dynamic content, changing component internally, etc) strictly after the state has been updated we pass a callback function as a second argument to setState function.

Example: In this example, we are using classbased component and printing a line to indicate that callback function gets executed just after the state updates, this can be used when we have to perform some code execution strictly after state updates, a simple use case for this scenario can be fetching any dynamic content through API, i.e. When we click on the algorithms section from the homepage of GFG it fetches the list of all topics, this can be done by GET request inside the callback function of setState which sets the algorithms button clicked.

App.js




import React from 'react';
import ReactDOM from 'react-dom';
  
class MyComponent extends React.Component {
    constructor(){
        super();
  
        this.state = {
            clicked:0
        }
    }
    stateManipulater = ()=>{
        this.setState((prevState)=>{
           return {clicked:prevState.clicked+1};
        }, ()=>{            
        console.log("This line will only get "
          + "printed after state gets updated");  
        })
    }
  
 render (){
    return <div><h3>Illustration of Working with State!</h3> 
          
    <p>
        This Button is associated with an integer state 
        which increments on click and UI re-renders 
        accordingly
    </p>
  
    <button onClick={this.stateManipulater} >
        {`Clicked ${this.state.clicked} Times`} 
    </button></div>
 }
}
  
ReactDOM.render(
    <MyComponent/>,    // What to Display
    document.getElementById('root')   // Where to Display
);

Output:

Explanation: This is the output of the above code, just after clicking on the button, the event gets generated which calls this.setState function to manipulate state, and immediately after that, the callback function passed as a second argument to this.setState executes, and the line gets printed on the console.

Now we will see how to use and manipulating state in functional components.

Syntax:

1. Initializing State: We have useState hook to work around with the state in the functional component, useState receives the initial State as an argument and returns the state variable along with a function that later can be used to set the state associated with it.

const [state, setState] = useState(intialState);

// Note:- You are not restricted to name state variable
// as "state" and function as "setState"

2. Accessing State: We can access state with name directly anywhere in a functional component like “state”. 

3. Manipulating State: The function we receive from useState is used to manipulate the associated state variable. 



  • Changing state object with a provided object as an argument while calling.
setState(arg);
  • When we have to update based on the previous state we pass a function that gets the previous state as a parameter.
setState((prevState)=>{
    // Do return a new state object after some manipulations 
});
  • Unlike class, the functional component doesn’t provide us the callback when the state has changed but the useEffect hook can be used to achieve the same, useEffect calls the given function whenever something from the dependency array changes.

Example: In this example, we are printing a line to indicate that callback function gets executed just after the state updates, this can be used when we have to perform some execution strictly after state updates, a simple use case for this scenario can be fetching any dynamic content through API, ie. When we click on the algorithms section from the homepage of GeeksforGeeks it fetches the list of all topics, this can be done by GET request inside the callback function of setState which sets the algorithms button clicked.

App.js




import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
  
function MyComponent (){
    const [state, setState] = useState({clicked:0});
  
    const stateManipulater = ()=>{
        setState((prevState)=>{
           return {clicked:prevState.clicked+1};
        })
    }
    useEffect(()=>{    
        console.log("This line will only get "
        + "printed after state gets updated");  
    }, [state])
  
    return <div><h3>Illustration of Working with State!</h3> 
        <p>
            This Button is associated with an integer
            state which increments on click and UI 
            re-renders accordingly 
        </p>
  
        <button onClick={stateManipulater} > 
        {`Clicked ${state.clicked} Times`} </button>
    </div>
}
  
ReactDOM.render(
    <MyComponent/>,    // What to Display
    document.getElementById('root')   // Where to Display
);

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Explanation: This is the output of the above code, just after clicking on the button the state gets changed by the event handler, and immediately after that, the component notices that something inside the dependency array of useEffect has been changed hence immediately executes its functionality and we have only written the console log inside it so the line gets printed just after the state change.

Points to remember while working with state:

1. Don’t ever change the State explicitly, because in this way react will not be able to observe the state changes, and the component’s behavior will not get affected, so always use the setState function provided by the component.

2. As you understood that state change causes re-render of components hence always keep an eye on the places where the state is changing, sometimes little mistakes may cause extra or in the worst case infinite re-renders, which will consequently make your application slower.  

3. If you have multiple elements in the state object or array, and you only have to change one element then don’t forget to spread the data otherwise it will overwrite the object/array with that single element because state updates as shallow merge.

4. After updating the state don’t rely on the fact that the state is surely updated, in some cases it may take a little bit of time due to the internal working of REACT, so if you have immediate use of updated state does create your own.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!