0
votes

At this page React Native State on React Native docs, we have the following statement:

props are set by the parent and they are fixed throughout the lifetime of a component.

But, at this page React State and Lifecycle on React docs, we have the following statement:

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

Where is my misunderstandment? For me the Lifecycle of a component would end when the component is removed from the DOM. So given the first statement i could access the this.props values at any part of my component not only on the render method, but this is not what the second statement says.

2

2 Answers

2
votes

The second statement just says that you should not use this.props or this.state to update your state because multiple updates will be batched by react. If you do e.g. this:

class MyComp extends React.Component{
    constructor(props) {
        super(props);

        this.state = {
            aValue: 0,
        };
    }

    componentDidMount() {
        this.setState({aValue: this.state.aValue + 1}); // should be 1 now
        this.setState({aValue: this.state.aValue + 1}); // should be 2 now
    }

    render() {
        return (
            <p>{this.state.aValue}</p>
        );
    }
}

If you do this chances are you end up with a state: {aValue: 1} because react will batch your updates leading to the second update overriding your first update, because this.state.aValue has not been updated in the moment the second call to setState() happens and is still 0.

Instead you have to pass a function to setState() that gets passed the new state and props and returns the next state:

this.setState((nextState, nextProps) => ({aValue: nextState.aValue + 1}));

There is nothing said about where you can access this.state or this.props.

2
votes

React and React Native props are behaving in completely the same manner. Both are passed from parent to children and shouldn't be mutated (edited) in the child component.