Clue Mediator

useState with the previous state in React Hooks

šŸ“…September 3, 2020
šŸ—ReactJS

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.

import React, { useState } from "react";

const HookCounter = () => {
  const [counter, setCounter] = useState(0);

  // handle button click event
  const handleClick = () => {
    setCounter(counter + 1);
  }

  // handle button click event to add 5 in counter
  const handleAddFiveClick = () => {
    for (let i = 0; i < 5; i++) {
      setCounter(counter + 1);
    }
  }

  return <div>
    <b>Counter - Hook Component</b><br><br>
    <label>Counter: {counter}</label><br><br>
    <button onclick={handleClick}>Add +1</button>Ā 
    <button onclick={handleAddFiveClick}>Add +5</button>
  </div>
}

export default HookCounter;

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.

// handle button click event to add 5 in counter
const handleAddFiveClick = () => {
  for (let i = 0; i < 5; i++) {
    setCounter(prevState => prevState + 1);
  }
}

Combine all code together and see how it looks.

HookCounter.js

import React, { useState } from "react";

const HookCounter = () => {
  const [counter, setCounter] = useState(0);

  // handle button click event
  const handleClick = () => {
    setCounter(counter + 1);
  }

  // handle button click event to add 5 in counter
  const handleAddFiveClick = () => {
    for (let i = 0; i < 5; i++) {
      setCounter(prevState => prevState + 1);
    }
  }

  return <div>
    <b>Counter - Hook Component</b><br><br>
    <label>Counter: {counter}</label><br><br>
    <button onclick={handleClick}>Add +1</button>Ā 
    <button onclick={handleAddFiveClick}>Add +5</button>
  </div>
}

export default HookCounter;

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

import React, { Component } from "react";

class ClassCounter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    }
  }

  // handle button click event
  handleClick = () => {
    this.setState({ counter: this.state.counter + 1 });
  }

  // handle button click event to add 5 in counter
  handleAddFiveClick = () => {
    for (let i = 0; i < 5; i++) {
      this.setState(prevState => ({ counter: prevState.counter + 1 }));
    }
  }

  render() {
    return <div>
      <b>Counter - Class Component</b><br><br>
      <label>Counter: {this.state.counter}</label><br><br>
      <button onclick={this.handleClick}>Add +1</button>Ā 
      <button onclick={this.handleAddFiveClick}>Add +5</button>
    </div>
  }
}

export default ClassCounter;

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