Performance is crucial for providing great user experience. Here are 10 essential React performance tips:
1. Use React.memo Wisely
// Don't wrap everything in memo
const ExpensiveComponent = React.memo(function ExpensiveComponent({ data }) {
return <div>{data.value}</div>
}, (prevProps, nextProps) => {
return prevProps.data.value === nextProps.data.value
})Only memoize components that:
- Re-render with same props frequently
- Render heavy UI without changing much
- Are used in lists
2. Lazy Load Routes
// Next.js makes this easy
import dynamic from 'next/dynamic'
const Dashboard = dynamic(() => import('./Dashboard'), {
loading: () => <div>Loading...</div>,
ssr: false
})3. Code Splitting
// Use dynamic imports for large components
const Chart = dynamic(() => import('@/components/Chart'))
// This creates a separate bundle for Chart4. Virtualize Long Lists
import { useVirtualizer } from 'react-window'
const VirtualList = () => {
const rowVirtualizer = useVirtualizer()
return (
<div style={{ height: '600px', overflow: 'auto' }}>
{rowVirtualizer({
height: 600,
count: 10000,
estimateSize: () => 50,
})}
{({ index, style }) => (
<div style={style}>Row {index}</div>
)}
</div>
)
}5. Avoid Anonymous Functions in Render
// ❌ Bad
<Component onClick={() => handleClick()} />
// ✅ Good
const handleClick = useCallback(() => {...}, [])
<Component onClick={handleClick} />6. Use Production Build
Always build for production:
npm run build
npm start7. Optimize Images
import Image from 'next/image'
<Image
src="/hero.jpg"
alt="Hero section"
width={1920}
height={height}
priority
blurDataURL="data:image/jpeg;base64,/..."
/>8. Debounce Search/Input
import { useDebounce } from 'usehooks-ts'
const [search, setSearch] = useState('')
const debouncedSearch = useDebounce(search, 500)9. Memoize Expensive Calculations
import { useMemo } from 'react'
const expensiveCalculation = useMemo(() => {
return data.reduce((acc, item) => acc + item.value, 0)
}, [data])10. Use React Profiler
import { Profiler } from 'react'
<Profiler id="App" onRender={(id, phase, actualDuration) => {
console.log(`${id} took ${actualDuration}ms`)
}}>
<App />
</Profiler>Conclusion
Implementing these performance tips will make your React apps significantly faster. Remember to measure before optimizing, and always profile your applications to identify bottlenecks.