React: Add useMount and useUpdate effect hooks

Created on 9 Jun 2019  路  3Comments  路  Source: facebook/react

Maybe I am overlooking something, but useMount and useUpdate seem to be useful.

// Ignore didMount. Behave like didUpdate. This should be part of React imho.
const didMountRef = useRef(false);
useEffect(() => {
  if (!didMountRef.current) {
    didMountRef.current = true;
    return;
  }
  saveDraftWebThrottled(document);
}, [document, saveDraftWebThrottled]);

Most helpful comment

+1 for this problem.

When you use useEffect with second parameter different than [], what you expect is it to run when that variable changes.

For instance:

useEffect(
  () => {
   //
  },
  [someParam]
)

But then, when it tries to render the first time too, while the someParam didn't change, this is not expected.

So why not to provide a 3rd parameter for useEffect to control if you don t want it to run the first time. I think it should not run for the initial render by default.

Please think about it. This is sth. I always need to deal with.

All 3 comments

We intentionally didn't do this in order to force you to deal with all cases earlier, and to write more resilient components.

In this particular example it would be better to just do

useEffect(() => {
  saveDraft(data);
}, [data]);

and then have saveDraft do the de-duplication like

let lastData
function saveData(data) {
  if (lastData === data) {
    return
  }
  lastData = data
  // save it here
}

Some components need to skip initial effect if they maintain own state computed from an initial prop. This is a pattern I have to use:

const isInitialRender = useRef(true);
// useEffect1 with if (isInitialRender.current) return;
// useEffect2 with if (isInitialRender.current) return;
useEffect(() => {
  isInitialRender.current = false;
}, []);

+1 for this problem.

When you use useEffect with second parameter different than [], what you expect is it to run when that variable changes.

For instance:

useEffect(
  () => {
   //
  },
  [someParam]
)

But then, when it tries to render the first time too, while the someParam didn't change, this is not expected.

So why not to provide a 3rd parameter for useEffect to control if you don t want it to run the first time. I think it should not run for the initial render by default.

Please think about it. This is sth. I always need to deal with.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

acdlite picture acdlite  路  83Comments

gaearon picture gaearon  路  227Comments

addyosmani picture addyosmani  路  143Comments

gaearon picture gaearon  路  126Comments

gabegreenberg picture gabegreenberg  路  119Comments