Performance Optimization
React is fast by default, but even fast things can be faster. Performance optimization is about removing unnecessary work so your app stays snappy as it grows.
The golden rule: do not optimize prematurely. Profile first, find the bottleneck, then fix it. Most React apps run fine without any manual optimization.
React.memo
React.memo prevents a component from re-rendering if its props have not changed. Think of it as a bouncer that only lets re-renders through when something actually changes.
import { memo } from 'react'
const ExpensiveList = memo(function ExpensiveList({ items }) {
console.log('ExpensiveList rendered')
return (
{items.map(item => (
- {item.name}
))}
)
})
function App() {
const [count, setCount] = useState(0)
return (
)
}
Without memo, ExpensiveList re-renders on every click even though its items prop never changes. With memo, it only renders once. The console log proves it.
useMemo and useCallback
useMemo caches expensive calculations. useCallback caches functions. Both prevent unnecessary re-computation on every render.
import { useMemo, useCallback } from 'react'
function FilteredList({ items, searchTerm }) {
const filtered = useMemo(() => {
return items.filter(item =>
item.name.toLowerCase().includes(searchTerm.toLowerCase())
)
}, [items, searchTerm])
const handleClick = useCallback((id) => {
console.log('Clicked item:', id)
}, [])
return (
{filtered.map(item => (
- handleClick(item.id)}>
{item.name}
))}
)
}
Without useMemo, filtering runs on every render. With it, filtering only runs when items or searchTerm change. Small wins add up in large apps.
Code Splitting and Virtualization
Code splitting loads only the code you need right now instead of everything upfront. React.lazy and Suspense handle this cleanly.
import { lazy, Suspense } from 'react'
const Dashboard = lazy(() => import('./Dashboard'))
function App() {
return (
Loading page...}>
)
}
Virtualization goes further for long lists. Libraries like react-window render only visible items instead of thousands. Your users get smooth scrolling instead of laggy nightmares.
Try it Yourself →