React Example

Performance Optimization

Master React performance optimization techniques

Memoization

Prevent unnecessary re-renders

useMemo Example

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 (
); }

React.memo Example

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 => ( ))}
    ); }

    Key Points

    • Memoize expensive calculations with useMemo
    • Prevent re-renders with React.memo
    • Optimize callback functions with useCallback
    • Only memoize when necessary

    Code Splitting

    Dynamic imports and lazy loading

    Lazy Loading Components

    import { lazy, Suspense } from 'react';
    
    // Instead of: import Dashboard from './Dashboard';
    const Dashboard = lazy(() => import('./Dashboard'));
    const Settings = lazy(() => import('./Settings'));
    
    function App() {
      return (
        }>
          
            } />
            } />
          
        
      );
    }

    Route-based Code Splitting

    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 }) => (
              }
              />
            ))}
          
        
      );
    }

    Key Points

    • Split bundle with dynamic imports
    • Lazy load components with React.lazy
    • Handle loading states with Suspense
    • Implement route-based code splitting

    Virtual Lists

    Handling large lists efficiently

    React Window Example

    import { FixedSizeList } from 'react-window';
    
    function Row({ index, style }) {
      return (
        
    Row {index}
    ); } function VirtualList() { return ( {Row} ); }

    Infinite Loading

    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}
    )}
    )}
    ); }

    Key Points

    • Render only visible items
    • Handle large datasets efficiently
    • Implement infinite scrolling
    • Optimize memory usage

    Pelajari Lebih Lanjut

    Tingkatkan skill React Anda dengan mempelajari topik lainnya