Open In App

How to Work with and Manipulate State in React ?

Working with and Manipulating state in React JS makes the components re-render on the UI by Updating the DOM tree. It makes sure to render the latest information and data on the interface.

Prerequisites:

These are the approaches to work with and Manipulate State in React JS.



Steps to Create 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:

 

Steps to Manipulate the State in Class Components:

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

1. Initializing state:

Syntax:

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. 

Example: This example implements the state access and manipulation in React JS Class Components.




// Filename - index.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
);

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 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.

Steps to Manipulate the State in Functional Components:

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.

Syntax:

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. 

setState(arg);
setState((prevState)=>{
// Do return a new state object after some manipulations
});

Example: This example implements the state access and manipulation in React JS functional components using the React JS Hooks




// Filename - index.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:


Article Tags :