Who likes React custom Hooks? ✋🏾

Here are 8 that I found especially helpful or particularly interesting 🤓

1️⃣ useInitialMount - returns whether or not the current render is the first

/thread 🧵👇🏾
2️⃣ usePrevious - returns the previous value of a prop or state

So common it's in the React Hooks FAQ but that one has a potential gotcha where prev value can get overwritten when comp re-renders for other reasons

This only updates prev value if it differs from new val

🧵👇🏾
3️⃣ useUniqueId - Returns a unique ID that remains constant across component renders. Great for auto-generating IDs for DOM elements

There was a proposal for a built-in Hook called `useOpaqueIdentifier` but I'm not sure what happened to it

(uses `useInitialMount` 😉)

🧵👇🏾
4️⃣ useIsMounted - returns whether or not the component is mounted. Useful for async effects that may return after the component has been unmounted

🧵👇🏾
5️⃣ useMedia - updates when the state of a CSS media query changes with `matchMedia`

(uses `useIsMounted` 😉)

🧵👇🏾
6️⃣ useRafState - creates an alternate `setState` method which only updates after `requestAnimationFrame`. Great for debouncing events that fire a lot

🧵👇🏾
7️⃣ useWindowScroll - tracks the window scroll position as it changes. Good for sticky elements, horizontal carousels, etc.

(uses `useRafState` to debounce 😉)

🧵👇🏾
8️⃣ useDeepCompareEffect - A `useEffect` alt using deep equality on deps instead of strict equality so using objects/arrays is easier in deps

Will need to update react-hooks/exhaustive-deps ESLint rule to validate this Hook too

Less performant so shouldn't use everywhere

🧵👇🏾
Flavors of most of these React custom Hooks can be found in the `react-use` package. It has tons more too that you should definitely check out 👍🏾

https://github.com/streamich/react-use

🧵👇🏾
You can follow @benmvp.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.