Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot get prevState from componentDidUpdate lifecycle hook in React.js v18.1.0

import React, { Component } from "react";

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

    handleIncrement = () => {
        this.setState({ counter: this.state.counter + 1 });
    };

    componentDidUpdate(prevState) {
        console.log("prevState", prevState);
    }

    render() {
        return (
            <React.Fragment>
                <p>{this.state.counter}</p>
                <button onClick={this.handleIncrement}>Increment</button>
            </React.Fragment>
        );
    }
}

export default Counter;

I want to access the prevState prop returned from the componentDidMount lifecycle method. However, I get an empty object when I console.log(prevState). Please find attached image of the same. I want the object of the previous state in the console.

prevState empty object

Please help me out whether I’m doing something syntactically wrong or it something unexpectedly breaking in the never version of React. I’d love to hear from you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

You have to specify both inputs (prevProps, prevState)

  componentDidUpdate(prevProps, prevState) {
    console.log("prevState", prevState.counter);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading