Skip to main content

Rerender Derived State

Source: .agents/references/coding-standard/vercel-react-best-practices/rules/rerender-derived-state.md

Metadata

  • title: Subscribe to Derived State
  • impact: MEDIUM
  • impactDescription: reduces re-render frequency
  • tags: rerender, derived-state, media-query, optimization

Content

Subscribe to Derived State

Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.

Incorrect (re-renders on every pixel change):

function Sidebar() {
const width = useWindowWidth() // updates continuously
const isMobile = width < 768
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}

Correct (re-renders only when boolean changes):

function Sidebar() {
const isMobile = useMediaQuery('(max-width: 767px)')
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}