Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Especially the lifecycle ones. The class based lifecycle methods are much more explicit and easy to reason about. Compare these for example:

    import React from 'react';

    class WindowWidth extends React.Component {
      state = { width: window.innerWidth };

      handleResize = () => {
        this.setState({ width: window.innerWidth });
      };

      componentDidMount() {
        window.addEventListener('resize', this.handleResize);
      }

      componentWillUnmount() {
        window.removeEventListener('resize', this.handleResize);
      }

      render() {
        return <p>Window width: {this.state.width}px</p>;
      }
    }

    export default WindowWidth;

and this

    import React, { useState, useEffect } from 'react';

    function WindowWidth() {
      const [width, setWidth] = useState(window.innerWidth);

      useEffect(() => {
        const handleResize = () => setWidth(window.innerWidth);

        window.addEventListener('resize', handleResize);
        return () => {
          window.removeEventListener('resize', handleResize);
        };
      }, []);

      return <p>Window width: {width}px</p>;
    }

    export default WindowWidth;
Whats going on here? I see it adds and removes a resize event listener… okay, when?What happens with the function it returns?

Why do I need to pass in an empty array? What could even go in there? What happens if I omit it (it is empty).

Where is the unmounting and mounting? What order do things happen in and when?

These have answers of course. The function runs according to the dependency array (prop, state, etc) and just on mount if empty. And the callback runs on unmount, if any. But you have to learn them. Before you do, it's magic. And when you step away, you have to re-learn it. And when it gets a bit more complicated, you're going to have to sit down and learn it better.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: