uidotdev / usehooks

A collection of modern, server-safe React hooks – from the ui.dev team

Home Page:https://usehooks.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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 a useEffect() only during the first render (mounting). The following implementation is how it could be done today with usehooks 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 using usehooks by reversing the if() 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.