@tracked
is a decorator for Preact that makes working with state values no different than properties on your component instance.
It's one 300 byte function that creates a getter/setter alias into state/setState() for a given key, with an optional initial value. The "magic" here is simply that it works as a property decorator rather than a function, so it appears to integrate directly into the language.
tracked
has no dependencies and works with any component implementation that uses this.state
and this.setState()
.
It's available on npm as tracked (can you believe it?):
npm install --save tracked
Bask in the glory:
class Example extends Component {
// initialize state.count with a value:
@tracked count = 1000;
updateCount = e => {
// updates state.count via setState()
this.count = e.target.value;
};
render() {
return (
<input
value={this.count} // it's just a value!
onChange={this.updateCount}
/>
);
}
}
It's a decorator, but you really don't need to care about that to see how things are working. Here's what's going on:
// this terse syntax:
@tracked a = 1;
// ... produces this:
Object.defineProperty(this, 'a', {
get: () => this.state.a,
set: v => this.setState({ a: v })
});
MIT probably