Using prevState with React, basic and complex

AntoineGGG
Geek Culture
Published in
4 min readJun 18, 2021

--

Photo by Karla Hernandez on Unsplash

How to use the famous “prevState” to modify our React state without overriding it !

Let start with a basic exemple (the -famous- counter) :

With a fresh new React App:

import "./App.css";
import React, { useState } from "react";
const App = () => {
const [mySuperCounter, setMySuperCounter] = useState(0);
const handleIncrement = () => {
setMySuperCounter(mySuperCounter + 1);
setMySuperCounter(mySuperCounter + 1);
setMySuperCounter(mySuperCounter + 1);
};
const handleReset = () => {
setMySuperCounter(0);
};
return (
<div className="App">
<div>
<button
className="super-button"
type="submit"
onClick={handleIncrement}>
Incrementor
</button>
<button className="super-button" type="submit" onClick= {handleReset}>
State Resettor
</button>
</div>
<div>{mySuperCounter}</div>
</div>
);
};
export default App;

Okay, let’s break down the explanation to make it clearer:

Here, we have a basic component consisting of a state called “mySuperCounter” and two buttons: one for incrementing the state and another for resetting it to 0.

If we examine the “handleIncrement” method, it may appear that each time we click on the “Incrementor” button, the state will be incremented by 3. However…

--

--