Using objects/arrays in deps for React useEffect can cause it to run the effect on *every* re-render even if contents are the same cuz the references are different
We've got a couple of options...
1️⃣ Depend on the obj properties instead of the entire obj
/thread 🧵👇🏾
2️⃣ Duplicate the object within the effect when the *entire* object is needed. useEffect then depends on the pieces needed to create the object
In general creating object literals is cheap so the perf wins from optimized useEffect should outweigh the duplication
🧵👇🏾
3️⃣ Memoize/cache the object w/ useMemo Hook if creating the object is too expensive to do it twice. The obj is now safe to use in deps
This is suggested by the `react-hooks/exhaustive-deps` ESLint rule (part of `eslint-plugin-react-hooks` which you should totally be using)
🧵👇🏾
4️⃣ Do it yourself by (ab)using useRef Hook when obj is passed as a prop & we still need the whole object in the effect. The ref will maintain "referential equality" and only change when the new vs old object do not deep equal 🤓🤯
(the eslint rule will be very unhappy tho)
🧵👇🏾
I go over these 4 options for optimizing the React useEffect Hook w/ object or array dependencies in greater detail in my latest post
BTW if you enjoy this sort of content, don't miss out and subscribe to the BenMVP Newsletter 😄
It's a weekly-ish frontend dev email where I share my posts about JS, TS, React, "divops" & more. Also notifications about my minishops & speaking engagements
I used to tell folks learning React to learn JS really well first. I had good intentions but was still gate-keeping 😔
But I do think knowing modern JS can really level-up your React skills and I've got top 10 features I think will help you be more awesome-r 🔥🔥
[🧵 thread]
1. ES Modules
I see lots of confusion about when to use named vs default imports. The import style depends on how it was exported (named or default)
Named imports go within the curly braces & the single default import is outside of them 🤓
2. Arrow functions
Arrow functions can exist everywhere within your React app. Some folks (like myself) replace all functions with arrows while others only use them in spots
They really win w/ character savings but for those unfamiliar w/ the syntax they can lose w/ clarity 🧐