I was reading this React related article. I have also looked at the discussion on closures and callbacks here and here and here.
In an example, given in the React related article, there are three components <App>, <Form>, <Button>
. <App>
passes a state value to <Form>
component during initialization and also during componentDidMount
lifecycle. <Form>
passes a callback function to <Button>
component along with the state value it received from <App>
.
class App extends React.Component {
state = { val: "one" }
componentDidMount() {
this.setState({ val: "two" })
}
render() {
return <Form value={this.state.val} />
}
}
const Form = props => (
<Button
onClick={() => {
alert(props.value)
}}
/>
)
When the button is clicked in the below <Button>
component, it alerts a stale value "one" instead of the latest value "two".
class Button extends React.Component {
.....
render() {
return (
<button onClick={this.props.onClick}>This one is stale</button>
)
}
}
The reason given in the React article for stale value is that the callback closes over props.value.
I do not understand how/why is the props.value being closed over in React component. The callback assignment in above is probably being done like this:
this.props.onClick = () => {
alert(props.value)
}
So why is the latest value not being picked up? How is the prop.value "closed over"?
The complete code is given here.