kpg
kpg

Reputation: 671

React componentDidUpdate lifecycle enters with null prevState

React 16.13.1

Newbie.

I add the componentDidUpdate lifecycle method to my component:

export default class MyComponent extends React.Component {

componentDidUpdate(prevProps, prevState) {
    console.log('componentDidUpdate');
    //this.state
}

render () { ... }

In an onChange handler I update the state and componentDidUpdate fires. However prevState enters as null. Also, within the method this.state is null.

Any ideas on what I'm doing wrong?

Upvotes: 0

Views: 635

Answers (2)

Muhammed B. Aydemir
Muhammed B. Aydemir

Reputation: 1015

prevState points to the state before the update (props or state changed), so its expected to be null in your case. You can initialize the state if you want:

export default class MyComponent extends React.Component {
    state = {} // initialize here

    componentDidUpdate(prevProps, prevState) {
        console.log('componentDidUpdate');
        //this.state
    }

    render() { ... }
}

Upvotes: 1

keikai
keikai

Reputation: 15146

Init the state first

Use constructor(), define the state data structure inside, as well as setting the init value of it.

class YourComponent extends React.Component<Props, State>{
  static defaultProps = {
    classes: {},
  };
  constructor(props: Props) {
    super(props);
    this.state = {
    };
  }
  componentDidUpdate(prevProps, prevState) {
  }
  ...
}

Upvotes: 1

Related Questions