Skip to content

Hooks - unmount and didUpdate #15129

@lichstam

Description

@lichstam

I'm opening this up at Dan's request from a twitter discussion:
https://twitter.com/lichstam/status/1106995545938247682

From Twitter:

I can fill in on this. The first example I would like to point to is a debouncing hook I've created that looks something like this:

useEffect(() => {
  const debounced = setTimeout(() => setDebounced(steps), 500);
  return () => clearTimeout(debounced);
}, [steps])

and then I have another one, that actually performs the request:

useEffect(request, [debounced])

And it all works fine, apart from when the component is mounted and unmounted.
In the class model I was able to make sure it never runs the first time and on unmounting I could clear the timeout and, if the state value differs from prop (yes I know, you shouldn't mirror your props but I have to debounce somewhere), I could just perform a last request before I unmount.
Furthermore, componentDidUpdate really made it easy preventing this from running the first time. I'm not quite sure how to approach this with hooks.
Perhaps I'm doing it all wrong but to Patrick's point, the class way was more straight forward.

Another example: I code in RN and use the Animated API a lot. I have cases that translates into something like this:

useEffect(() => {
  if (inAddStage) moveAndShowStep(); // Animate with Animated API
}, [inAddStage]);

This works well but it does perform an unnecessary initial run which makes me wonder if I've missed the point with hooks (again, to Patrick's point, it seems a bit more complex sometimes). Why isn't there a hook that doesn't run the first time btw? Again, with the old lifecycles it was much clearer how to prevent this from happening (using componentDidUpdate).

On a last note, I just want to say that I'm very fond of the idea and wholeheartedly support the functional approach and I really like the concept of hooks being "state observers", that react only when the specified attributes change - which basically makes the whole code more declarative.
I've just started using them so I'll probably figure things out along the way but I thought I could give you something since you didn't get any answer :)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions