HomeReact
Chapter 22
07 — React Performance
Memoization
import { memo, useMemo, useCallback } from 'react';
const MemoizedComponent = memo(({ data }) => {
return <div>{data}</div>;
});
function Expensive({ items }) {
const computed = useMemo(() => expensiveCalc(items), [items]);
const callback = useCallback(() => doSomething(), []);
return <MemoizedComponent data={computed} onClick={callback} />;
}Lazy Loading
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</React.Suspense>
);
}Code Splitting
// Dynamic import
import('module').then(module => {
// Use module
});
// React.lazy + Suspense
const OtherComponent = lazy(() => import('./OtherComponent'));Key Takeaways
- Use
memofor preventing re-renders useMemofor expensive calculationsuseCallbackfor stable function references- Lazy load non-critical components
- Split code by routes/features