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]);
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.
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:
But then, when it tries to render the first time too, while the
someParamdidn'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.