Non-state variables in Components #3735
-
I'm afraid I can't remember where I read this, but it's been bugging me. I need a sanity check. 😅 The other day I stumbled across a comment in Preact internals discussion suggesting you can only store values in a component's state, and the reason was something to do with the component forgetting it. That made no sense to me. It's possible the writer misspoke or the context was DOM, I'm not sure. The problem is I don't really see this documented anywhere (though it pops up in Here's a short example that stores values inside the component instance other than import {h, Component} from 'preact';
const SOME_CONSTANT = "Is it four?";
export default class MyButton extends Component {
constructor(props) {
super(props);
this.state = {
'isFour': false
};
this.cached = null;
this.hardWork = this.hardWork.bind(this);
}
componentDidMount() {
this.hardWork();
}
hardWork() {
if (!this.cached) {
this.cached = {'complicated': 2+2};
}
this.setState({'isFour': this.cached.complicated == 4});
}
render({}, {isFour}) {
return <div onClick={this.hardWork}>{SOME_CONSTANT} {isFour}</div>;
}
} I always assumed this was totally fine, especially the bind's. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Huh, that would be new to me. I'm curious where you read that. It's perfectly fine to store things on the class instance itself and we even do that ourselves in all of our addons like hooks/signals/etc. Storing things on the class instance is a fundamental aspect of having class components in the first place. |
Beta Was this translation helpful? Give feedback.
Huh, that would be new to me. I'm curious where you read that. It's perfectly fine to store things on the class instance itself and we even do that ourselves in all of our addons like hooks/signals/etc. Storing things on the class instance is a fundamental aspect of having class components in the first place.