Master React performance optimization techniques
Prevent unnecessary re-renders
import { useMemo, useState } from 'react';
function ExpensiveCalculation({ numbers }) {
const total = useMemo(() => {
console.log('Computing sum...');
return numbers.reduce((acc, num) => acc + num, 0);
}, [numbers]); // Only recompute when numbers change
return Total: {total};
}
function MemoExample() {
const [numbers] = useState([1, 2, 3, 4, 5]);
const [count, setCount] = useState(0);
return (
);
}
import { memo } from 'react';
const TodoItem = memo(function TodoItem({ todo, onToggle }) {
console.log('TodoItem render');
return (
onToggle(todo.id)}
/>
{todo.text}
);
});
function TodoList({ todos, onToggle }) {
return (
{todos.map(todo => (
))}
);
}
Dynamic imports and lazy loading
import { lazy, Suspense } from 'react';
// Instead of: import Dashboard from './Dashboard';
const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));
function App() {
return (
}>
} />
} />
);
}
const routes = [
{
path: '/',
component: lazy(() => import('./Home')),
},
{
path: '/about',
component: lazy(() => import('./About')),
},
{
path: '/contact',
component: lazy(() => import('./Contact')),
}
];
function App() {
return (
}>
{routes.map(({ path, component: Component }) => (
}
/>
))}
);
}
Handling large lists efficiently
import { FixedSizeList } from 'react-window';
function Row({ index, style }) {
return (
Row {index}
);
}
function VirtualList() {
return (
{Row}
);
}
import { useState } from 'react';
import { FixedSizeList as List } from 'react-window';
import InfiniteLoader from 'react-window-infinite-loader';
function InfiniteList() {
const [items, setItems] = useState([]);
const [hasNextPage, setHasNextPage] = useState(true);
const [isNextPageLoading, setIsNextPageLoading] = useState(false);
const loadMoreItems = async (startIndex, stopIndex) => {
setIsNextPageLoading(true);
const newItems = await fetchItems(startIndex, stopIndex);
setItems(prev => [...prev, ...newItems]);
setIsNextPageLoading(false);
};
return (
!hasNextPage || index < items.length}
itemCount={hasNextPage ? items.length + 1 : items.length}
loadMoreItems={loadMoreItems}
>
{({ onItemsRendered, ref }) => (
{({ index, style }) => (
{items[index].content}
)}
)}
);
}
Tingkatkan skill React Anda dengan mempelajari topik lainnya