I have a variable that I'm creating in componentDidMount()
and I'd like it to be available in componentDidUpdate()
. Any thoughts? Code looks like this:
class Example extends Component {
componentDidMount() {
const myVariable = 'this thing';
}
componentDidUpdate() {
// I'd like my variable to be accessible here
console.log(myVariable);
}
render() {...}
}
componentDidMount() only runs once after the first render. componentDidMount() may be called multiple times if the key prop value for the component changes. componentDidMount method is used for handling all network requests and setting up subscriptions during the mounting phase.
The componentDidMount() method will be triggered as soon as the component is mounted or inserted into the DOM. The basic syntax to use componentDidMount() is looks like this. This method used widely by developers because it loads immediately once the component is mounted.
The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.
There is some fundamental misunderstanding here, you can still call the functions inside componentDidMount , however you should not define them inside it.
Save it to the component then.
componentDidMount() {
this.myVariable = 'this thing';
}
componentDidUpdate() {
// I'd like my variable to be accessible here
console.log(this.myVariable);
}
Also, as @Gosha Arinich helpfully pointed it out - be aware that if you do plan to re-use this variable throughout the component's lifecycle and update it and/or render it - it is best placed into the state
of the component (this.state
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With