Main ways to optimize React applications:
// Optimization examples:
// React.memo for components
// useMemo for heavy calculations
// useCallback for functions
// lazy for code splittingOptimizing a React application is like cleaning a room: remove unnecessary things, organize, and everything works faster! 🧹⚡
React.memo is like a filter that blocks useless re-renders:
// Component re-renders only if props changed
const MyComponent = React.memo(({title, count}) => {
return <div>{title} {count}</div>;
});When to use:
useMemo is like a calculator with memory, remembers the result:
// Heavy calculations done only when needed
const expensiveValue = useMemo(() => {
return heavyCalculation(data);
}, [data]);When to use:
useCallback is like a function storage, doesn’t create new ones each time:
// Function created once and saved
const handleClick = useCallback(() => {
doSomething();
}, []);When to use:
Lazy loading is like streaming: loads only what’s needed now:
// Component loads only when needed
const LazyComponent = lazy(() => import('./HeavyComponent'));Benefits:
Virtualization is like a train window: you see only what’s nearby:
// Renders only visible list elements
// Others load when scrollingWhen to use:
Code splitting is like a book by chapters: loads by need:
// Different app parts in different files
// Load only when navigating to pageBenefits:
// ❌ Bad — new function every render
<button onClick={() => doSomething()}>Button</button>
// ✅ Good — same function always
const handleClick = useCallback(() => doSomething(), []);
<button onClick={handleClick}>Button</button>// ❌ Bad — object created every time
<List data={{filter: 'active', sort: 'name'}} />
// ✅ Good — object doesn't change
const listConfig = useMemo(() => ({
filter: 'active',
sort: 'name'
}), []);
<List data={listConfig} />// ❌ Mistake — optimization not always needed
const SimpleComponent = React.memo(() => <div>Just text</div>);
// ✅ Correct — optimize only "heavy" things
const HeavyComponent = React.memo(({data}) => {
// Complex render
});// ❌ Mistake — forgot dependency
const value = useMemo(() => calculate(a), []); // a not in list!
// ✅ Correct — all dependencies listed
const value = useMemo(() => calculate(a), [a]);Proper React application optimization makes them faster and more pleasant to use! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪