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

I think your exercise framing is silly but I’ll bite since I’m a programming addict. Writing on my phone so forgive any typos.

    function useInterval(cb, ms, deps) {
      useEffect(() => {

        const id = setInterval(cb, ms)
        return () => cancelInterval(id)

      }, [ms, …deps])
    }

I think this is much nicer than having interval maintenance and prop diffing is didMount, didUpdate, and willUnmount. Certainly it’s easier to get the hooks right (for me) and all the logic ends up in contiguous lines of code. It’s a higher level interface so it takes a bit more practice to apply - feels like Ocaml more than Java.


I think the original comment is fair, and comparing your attempt to working solutions online will reveal the complexity of bugs that can arise from hooks.


I see - the issue with my solution is that the interval will reset whenever the deps array changes, starting over the delay? The implicit "state" of the time left before the next tick is destroyed when the effect re-runs - instead this should persist.

Dan Abramov has a good post that explains the issue here well: https://overreacted.io/making-setinterval-declarative-with-r...


Also the id must be hold using useRef().

That's the whole problem with hooks: when things are easy, they are nice. When things are complicated, unfortunately, they look easy, and you start to think you understand what's going on. But most people, me included, don't.


I don't think you need to hold id using useRef(). The cleanup callback holds the id from the same render, so it will clean up the correct interval.


> When things are complicated, unfortunately, they look easy, and you start to think you understand what's going on. But most people, me included, don't.

That’s fair. The other side of the coin is that class components have their own kinds of failure modes. I have fixed a lot of buggy class components that simply forget that props change - they do some kind of effect-y thing using the first props during didMount, and then never respond to prop changes aside from `render()`. With hook components, the linter will get mad about that sort of thing. In either case there’s gotchas, but I like that useEffect helps people avoid leaking and think about changing props.




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

Search: