|
|
|
|
|
by idreyn
1185 days ago
|
|
Hooks let you colocate logic that, in class components, would need to be split across multiple lifecycle methods. In practice you need to remove the event listener when the component unmounts. You can get reasonably close to a hooksy API for doing this here: class MyComponent {
componentWillMount() {
this.stopWatchingViewport = watchViewPort((x, y) => {
this.setState({ something: x + y });
});
}
componentWillUnmount() {
this.stopWatchingViewport();
}
}
watchViewPort(callback) {
const onResize = (event) => {
// get x and y
callback(x, y);
};
addEventListener("resize", onResize);
return () => removeEventListener("resize", onResize);
}
But being able to slice up logic by functionality, rather than by lifecycle event, gets gradually nicer as you have more of it. |
|
The hook API could be class based:
You would be able to use it in a component like this Boring, and a bit less weird.