Engineering•Aug 2, 2023•2 min read
Optimizing React Performance
Practical tips on using memoization, lazy loading, and code splitting to make your React applications fly on mobile devices.
BD
Bang Den
Frontend Engineer & Designer
Table of Contents
Why Performance Matters
A 1-second delay in page response can result in a 7% reduction in conversions. On mobile, this is even more critical.
1. React.memo for Component Memoization
Prevent unnecessary re-renders:
TypeScript (TSX)
1const ExpensiveComponent = React.memo(({ data }) => {2 return (3 <div>4 {data.map(item => (5 <Item key={item.id} {...item} />6 ))}7 </div>8 );9});
2. useMemo and useCallback
useMemo for Expensive Calculations
TypeScript (TSX)
1const sortedItems = useMemo(() => {2 return items.sort((a, b) => a.name.localeCompare(b.name));3}, [items]);
useCallback for Stable References
TypeScript (TSX)
1const handleClick = useCallback((id) => {2 setSelectedId(id);3}, []);
3. Code Splitting with Dynamic Imports
TypeScript (TSX)
1const HeavyComponent = dynamic(() => import('./HeavyComponent'), {2 loading: () => <Skeleton />,3 ssr: false4});
4. Virtual Lists for Large Data Sets
Don't render thousands of items – virtualize them:
TypeScript (TSX)
1import { FixedSizeList } from 'react-window';23<FixedSizeList4 height={400}5 itemCount={10000}6 itemSize={35}7>8 {Row}9</FixedSizeList>
5. Image Optimization
Use Next.js Image component:
TypeScript (TSX)
1<Image2 src="/photo.jpg"3 alt="Photo"4 width={800}5 height={600}6 placeholder="blur"7 loading="lazy"8/>
Performance Checklist
- [ ] Audit with Lighthouse
- [ ] Use React DevTools Profiler
- [ ] Enable production builds
- [ ] Implement error boundaries
- [ ] Monitor Core Web Vitals
Conclusion
Performance optimization is an ongoing process. Start with the biggest wins and iterate from there.