Comment

Comment by idreyn

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.
parent idreyn 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton