Open In App

How to get previous state in ReactJS Functional Component ?

Improve
Improve
Like Article
Like
Save
Share
Report

To get the previous state in ReactJS Functional Component we can use the previous value of the state while using the set state method. State can only be directly accessed in the class component so we will be using the react useState hook to accomplish the task.

Prerequisites

Steps to create React Application

Step 1: Create React Project 

npm create-react-app myreactapp

Step 2: Move to the Project Directory

cd myreactapp

Project Structure:

Example: This example demonstrate the use of setstate method form usestate to get the previoues state an display in another state variable.

JavaScript




// Filename - App.js
 
import React, { useState } from "react";
 
const App = () => {
    const [number, setNumber] = useState(0);
    const [previousValue, setPreviousValue] =
        useState(null);
 
    return (
        <div
            style={{
                textAlign: "center",
                alignItems: "center",
                margin: "auto",
            }}
        >
            <h1 style={{ color: "green" }}>
                GeeksforGeeks
            </h1>
            <h3>
                React Example to excess previous state in
                Funtional components
            </h3>
            <h4>number: {number}</h4>
            <h4>previous number: {previousValue}</h4>
            <button
                onClick={() =>
                    setNumber((previous) => {
                        setPreviousValue(previous);
                        return previous + 1;
                    })
                }
            >
                increment
            </button>
        </div>
    );
};
 
export default App;


Step to run the application: To run the app while you are in the same folder of the application in the terminal by this command:

npm start

Output: This output will be visible on the http://localhost:3000/ on the browser window.

Peek-2023-10-30-12-33



Last Updated : 02 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads