News for hackers. Stuff that matters.
Re:Thinking in React Hooks by atombender on Thursday December 12, 2019 @02:57PM (#21775694)
I have the opposite view. The things you mentioned (componentDidMount, etc.) are actually hard to get right, and class-based components don't help by scattering the logic all over the place.

Functional components force your component lifecycle into a funnel where the lifecycle becomes obvious, because all the inter-dependencies are already there.

For componentDidMount, you can replicate this easily with hooks:

  const Hello = () => {
    const mounted = useRef(false)
    useEffect(() => {
      if (!mounted.current) {
        mounted.current = true
        console.log("Mounted!");
      }
    }, [])
    return <>Hello</>
  }
Extracting anything into a hook is trivial:

  function useMounted(f) {
    const mounted = useRef(false)
    useEffect(() => {
      if (!mounted.current) {
        mounted.current = true
        f()
      }
    }, [])
  }

  const Hello = () => {
    useMounted(() => {
      console.log("Mounted!");
    })
    return <>Hello</>
  }
Implementing an unmount callback is also trivial.

The useMounted() example, coincidentally, shows a real benefit to hooks: Easy extraction of reusable logic. Hooks are like plugins this way. For example, one hook I've written that I use all the time is this [1], it lets you get a callback every time your component resizes. If you were to do this with a class-based component, you'd have to use an ugly HOC, which results in lots of unnecessary wrapping/nesting.

For componentDidUpdate, useMemo() is arguably easier to deal with.

[1] https://gist.github.com/atombender/b95bbd2014f6a3ec303b843a9...

Re:Thinking in React Hooks by ArchReaper on Thursday December 12, 2019 @04:11PM (#21776521)
Unless I'm missing something, you don't need all that just to have 'componentDidMount' eg:

    export const useMounted = (f) => {
      useEffect(f, []);
    }
Edit: originally:

    export const useMounted = (f) => {
      useEffect(() => {
        f();
      }, []);
    }
Re:Thinking in React Hooks by atombender on Thursday December 12, 2019 @04:22PM (#21776628)
Ah, of course. The use of dependency lists in React is something I keep forgetting exist. Thanks.
Re:Thinking in React Hooks by acemarke on Thursday December 12, 2019 @04:12PM (#21776524)
And to code-golf it a bit further, it can just be:

    useEffect(f, [])