I was reading an article (link) about the difference between functional and class components. The article links to a sandbox which is what this question refers to (link).
In the article, we have this class component:
class ProfilePage extends React.Component {
showMessage = () => {
alert('Followed ' + this.props.user);
};
handleClick = () => {
setTimeout(this.showMessage, 3000);
};
render() {
return <button onClick={this.handleClick}>Follow</button>;
}
}
This component is rendered in a parent component that passes it a user
prop. If you click on the button, and then change the user
in the parent component, the alert that shows up will display the "incorrect" user, ie it will display the current value of the user
prop, not the one that was current when the button was clicked. I don't understand why this is.
The article explains it as:
This class method reads from this.props.user. Props are immutable in React so they can never change. However, this is, and has always been, mutable.
Indeed, that’s the whole purpose of this in a class. React itself mutates it over time so that you can read the fresh version in the render and lifecycle methods.
First, I see that class methods are being used, but aren't props available on the instance (ie the React element, which is a JS object instance)? I probably have an incorrect understanding here of how React is actually functioning under the hood.
Second, the class methods are being used to be able to have this
be the Component itself (ie the JavaScript class). Again, my doubt about where props are actually stored. I thought it was on the instance, the generated React element.
Third, with the above answers I might be able to answer this but: what does React mutate over two renders? I thought it was the particular JS object (React element) that is the result of calling render.
Edit:
1) So the "class methods" I mentioned are "Class fields", and this is syntactic sugar for defining the fields on this
in the constructor. So in fact these methods belong to the instances.
2) The "class methods" are defined as arrow functions, so when they are actually placed on this
in the constructor, they are bound to what this
is in the constructor.
3) Therefore, yes, props are on an instance, but the question for me remains: We have one particular object with a set of props, and it sets the setTimeout to call this.showMessage; then I guess React replaces this with a new version of the object, but why does the this
on the callback on the original object change?