Tuesday, November 19, 2024
Google search engine
HomeLanguagesHow to get previous state in ReactJS Functional Component ?

How to get previous state in ReactJS Functional Component ?

When you build a React app Getting a previous state for a component is a situation we may face, so how do we do that professionally and save a certain value of a state all over the component’s life.

Before diving into this subject, I would talk in brief about how React component renders, and what happens when we update a state. At first render, all variables and functions are defined and take their space in memory, and in every update in any state, all variables and functions are redefined again. I would talk about objects in particular. When a component re-renders all objects in the component are redefined objects may take another address in memory, and this optimization issue we will take about it later.

Setting up the Project:

Step 1: Create the project folder and move into it:

mkdir foldername
cd foldername

Step 2: At first, we create react app with this command:

npx create-react-app MyApp

Project Structure: here is the project structure:

 

Step 3: So, is there s a way  I can access the previous state by knowing every re-render all variables and functions are redefined? It is yes, I can access the previous state through setState the asynchronous function like this in the next example. MyComponent.jsx

JavaScript




// Filename: MyComponent.jsx
import { useState } from "react";
 
export const MyComponent = () => {
    const [number, setNumber] = useState(0);
    return (
        <div>
            <h5>{number}</h5>
            <button onClick={() => setNumber((previous) => previous + 1)}>
                increment
            </button>
        </div>
    );
};


Step 4: Ok, but there is a way to capture the previous state over the components and access it anywhere in the component? yes there is a way, by using useRef hook I can save the previous state, we know that the useRef hook works with elements through the dom, but we can also use it in this. The value of useRef doesn’t change when the component is re-rendered, we can say it is as state except it does not cause re-rendering when it is updated, we can see this in the next example :

JavaScript




// Filename: MyComponent.jsx
import { useEffect, useRef, useState } from "react";
 
export const MyComponent = () => {
    const [number, setNumber] = useState(0);
    const previousValue = useRef(null);
 
    useEffect(() => {
        previousValue.current = number;
    }, [number]);
 
    return (
        <div>
            <h5>number: {number}</h5>
            <h5>previous number: {previousValue.current}</h5>
            <button onClick={() => setNumber((previous) => previous + 1)}>
                increment
            </button>
        </div>
    );
};


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: 

 

And by knowing useEffect when it renders and the component life cycle we can achieve this easily.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments