Rerender Dependencies
Source: .agents/references/coding-standard/vercel-react-best-practices/rules/rerender-dependencies.md
Metadata
- title: Narrow Effect Dependencies
- impact: LOW
- impactDescription: minimizes effect re-runs
- tags: rerender, useEffect, dependencies, optimization
Content
Narrow Effect Dependencies
Specify primitive dependencies instead of objects to minimize effect re-runs.
Incorrect (re-runs on any user field change):
useEffect(() => {
console.log(user.id)
}, [user])
Correct (re-runs only when id changes):
useEffect(() => {
console.log(user.id)
}, [user.id])
For derived state, compute outside effect:
// Incorrect: runs on width=767, 766, 765...
useEffect(() => {
if (width < 768) {
enableMobileMode()
}
}, [width])
// Correct: runs only on boolean transition
const isMobile = width < 768
useEffect(() => {
if (isMobile) {
enableMobileMode()
}
}, [isMobile])