Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useEffect only on update (or only on mount) #40

Open
gnapse opened this issue Oct 28, 2018 · 4 comments
Open

useEffect only on update (or only on mount) #40

gnapse opened this issue Oct 28, 2018 · 4 comments

Comments

@gnapse
Copy link

gnapse commented Oct 28, 2018

Even though the documentation says it's a rare thing, I'm bothered by the fact that there's no built-in way to control if you want useEffect to run only on component update, and not on first mount.

I was thinking of creating either this:

useEffectOnUpdate(() => {
  // ...
});

or this:

useEffectEnhanced((isComponentUpdate) => {
  if (isComponentUpdate) {
    // ...
  }
});

on mount

Not to mention that the official way to restrict useEffect to run only on mount is not very clear or self-explanatory at all:

useEffect(() => {
  // ...
}, []);

Maybe I can combine these two gripes to provide these two useEffect alternatives: useEffectOnMount, useEffectOnUpdate. Would also like to provide the third alternative that always run, but receives a flag isComponentUpdate or isComponentMount, but I'm not sure about that, or what to call it (useEffectEnhanced is not very clear in its intention too 😕).

Thoughts?

@kivervinicius
Copy link

kivervinicius commented Apr 16, 2019

useEffect(function onMount () {
        console.log("onMount");
}, []);
useEffect(function onUpdate () {
     console.log("onUpdate");
}, [props.myProp]);

@gnapse
Copy link
Author

gnapse commented Apr 16, 2019

The thing is that this

useEffect(function onUpdate () {
     console.log("onUpdate");
}, [props.myProp]);

Runs not only on update of props.myProp, but also on mount.

@kivervinicius
Copy link

@gnapse I understand, well in that case when this need arises I would not add the onMount events to the onUpdate, however you're right ...

@milesegan
Copy link

I'd like to see a nicer solution to this too. It's a very common use case and having to manually create and manage a ref just to distinguish mount vs update seems like a very clunky fix for an otherwise very elegant API.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants