FR: useEffectOnce() and useUpdateEffect()
rentalhost opened this issue · comments
Hello, I wanted to mention some use
that I find interesting from another library called usehook-ts. Technically, both are currently possible, but it's a bit more verbose, so to speak. The suggestions aim to make the process simpler and cleaner.
useEffectOnce()
-
useEffectOnce()
: performs auseEffect()
only during the first render (mounting). The following implementation is how it could be done today withusehooks
versus the suggestion:
Using usehooks
:
const firstRender = useIsFirstRender();
useEffect(() => {
if (firstRender) {
// do something...
}
}, []);
With the suggestion:
useEffectOnce(() => {
// do something.
});
useUpdateEffect()
-
useUpdateEffect()
: this is the opposite of the function above: it only runs from the second render. You can achieve the same usingusehooks
by reversing theif()
condition.
I debated adding these initially, but decided against it. From a philosophical perspective, I think these go against the mental model for how effects should work in React.