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 is life.
Before diving into this subject, I would talk in a 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 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
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 :
Step to run the application: To run the app while you are in the same folder of application in the terminal by this command:
And by knowing useEffect when it renders and component life cycle we can achieve this easily.