Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/advanced-use-latest.md
1---2title: useEffectEvent for Stable Callback Refs3impact: LOW4impactDescription: prevents effect re-runs5tags: advanced, hooks, useEffectEvent, refs, optimization6---78## useEffectEvent for Stable Callback Refs910Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.1112**Incorrect (effect re-runs on every callback change):**1314```tsx15function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {16const [query, setQuery] = useState('')1718useEffect(() => {19const timeout = setTimeout(() => onSearch(query), 300)20return () => clearTimeout(timeout)21}, [query, onSearch])22}23```2425**Correct (using React's useEffectEvent):**2627```tsx28import { useEffectEvent } from 'react';2930function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {31const [query, setQuery] = useState('')32const onSearchEvent = useEffectEvent(onSearch)3334useEffect(() => {35const timeout = setTimeout(() => onSearchEvent(query), 300)36return () => clearTimeout(timeout)37}, [query])38}39```40