How can getDerivedStateFromProps method can access state if the state is initialized from within the constructor(props)?

Viewed 129

Hi all I am new to ES6 and React and I am stuck in component lifecycle-creation of react. My question is In my constructor I have initialized state..

constructor(props) {
    super(props);
    this.state = {
    ....something
}

Now in the Component Lifecycle Creation in react we have getDerivedStateFromProps which is a static function which takes two arguments props and previous state and you might return the current state or so depending if you are changing the state from props or not

static getDerivedStateFromProps (props, state) {
    ... do something
    return state;
}

How is this static function able to access or have a property which is initialized in constructor() which will run at runtime or when the object is created ? Isn't the static function runs before runtime at class loading time so how is it able to access state object ?

1 Answers

and you might return the current state or so depending if you are changing the state from props or not

No, you return a state update (things to change, not complete state [although complete state is okay too]), or don't return anything / return undefined for no update.

How is this static function able to access or have a property which is initialized in constructor() which will run at runtime or when the object is created ?

It doesn't. React calls the function passing in the state as an argument, as you said. Think of the React code that calls this as looking vaguely like this:


const stateUpdate = YourComponentClass.getDerivedStateFromProps(
    componentInstance.state,
    componentInstance.props
);
// (Then it uses `stateUpdate` to set the state immediately)

I'm sure it's not really that, but conceptually, that's what it's doing.

getDerivedStateFromProps is static so that people don't do things in it that mutate the instance, because they don't have access to the instance.

Related