useState with the previous state in React Hooks

Today we’ll show you how to use the useState with the previous state in React Hooks. In this article, we will explain to you why we need it and how to use the previous state value for the current process with an example.

Use prevState in useState React Hooks

  1. Create counter application using useState
  2. Add HTML element to update UI
  3. Implement logic using previous state
  4. Implement the same example using setState
  5. Output

1. Create counter application using useState

Let’s take a counter example where we will add two buttons and one label to implement an example.

Here we will use the useState hook to create a counter example so I will recommend you to check the following article before continuing the demo.

useState Hook in React

2. Add HTML element to update UI

Now, let’s add the one more button to increase the counter by 5 with the help of the loop. In this step, we will use the previous article’s method to update the counter in loop.

Check out the following code and see how it works.

If you run the above code then you can see the counter value is not getting increased by 5. It’s only increasing by 1. So let’s fix it in the next step using the previous state value.

3. Implement logic using previous state

Here we will update the logic of the handleAddFiveClick function where we will use the previous state value to update the current state. Update the following function in the above code.

Combine all code together and see how it looks.

HookCounter.js

Note: If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
Reference Link  |  Example

4. Implement the same example using setState

Now implement the same example using setState in the class component. Check out the following link for more information.

State in React JS

ClassCounter.js

5. Output

Run the project and check the output in the browser.

Output - useState with the previous state in React Hooks - Clue Mediator
Output – useState with the previous state in React Hooks – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *