React ve Next.js Performans Optimizasyonu: Hızlı Web Uygulamaları

React ve Next.js uygulamalarında performans optimizasyonu teknikleri. Code splitting, lazy loading, SSR ve modern optimizasyon yöntemleri.

Giriş: Performans Neden Önemli?

Modern web uygulamalarında performans, kullanıcı deneyimini doğrudan etkileyen kritik bir faktördür. React ve Next.js ile geliştirilen uygulamalarda doğru optimizasyon teknikleri kullanarak, hızlı ve verimli web uygulamaları oluşturabilirsiniz.

"1 saniye gecikme, sayfa görüntülenmelerinde %11, müşteri memnuniyetinde %16 ve dönüşüm oranlarında %7 azalmaya neden olur." - Amazon

1. React Performans Optimizasyonu

React.memo ile Gereksiz Render'ları Önleme

React.memo, bileşenlerinizi memoize ederek gereksiz yeniden render işlemlerini önler:

import React, { memo } from 'react';

const ExpensiveComponent = memo(({ data, onUpdate }) => {
  console.log('Component rendered');
  
  return (
    

{data.title}

{data.description}

); }); // Shallow comparison için custom comparison function const areEqual = (prevProps, nextProps) => { return prevProps.data.id === nextProps.data.id && prevProps.data.title === nextProps.data.title; }; export default memo(ExpensiveComponent, areEqual);

useMemo ve useCallback Hook'ları

Pahalı hesaplamaları ve fonksiyonları memoize edin:

import React, { useMemo, useCallback, useState } from 'react';

const DataProcessor = ({ items }) => {
  const [filter, setFilter] = useState('');
  
  // Pahalı hesaplamayı memoize et
  const processedData = useMemo(() => {
    return items
      .filter(item => item.name.includes(filter))
      .sort((a, b) => a.priority - b.priority)
      .map(item => ({
        ...item,
        processed: true,
        timestamp: Date.now()
      }));
  }, [items, filter]);
  
  // Callback fonksiyonunu memoize et
  const handleFilterChange = useCallback((event) => {
    setFilter(event.target.value);
  }, []);
  
  return (
    
{processedData.map(item => (
{item.name}
))}
); };

Virtual Scrolling

Büyük listeler için virtual scrolling kullanın:

import { FixedSizeList as List } from 'react-window';

const VirtualizedList = ({ items }) => {
  const Row = ({ index, style }) => (
    
{items[index].name}
); return ( {Row} ); };

2. Next.js Optimizasyonları

Image Optimization

Next.js Image bileşeni ile otomatik görsel optimizasyonu:

import Image from 'next/image';

const OptimizedImageComponent = () => {
  return (
    
Hero Image {/* Responsive images */} Responsive
); };

Code Splitting ve Dynamic Imports

Kod bölümleme ile bundle boyutunu küçültün:

import dynamic from 'next/dynamic';
import { Suspense } from 'react';

// Component-level code splitting
const DynamicChart = dynamic(() => import('../components/Chart'), {
  loading: () => 

Loading chart...

, ssr: false // Client-side only rendering }); // Conditional loading const DynamicModal = dynamic(() => import('../components/Modal')); const HomePage = () => { const [showModal, setShowModal] = useState(false); return (

Home Page

{showModal && ( Loading modal...
}> setShowModal(false)} /> )}
); };

Static Generation ve ISR

Static Site Generation ve Incremental Static Regeneration:

// pages/blog/[slug].js
export async function getStaticProps({ params }) {
  const post = await fetchPost(params.slug);
  
  return {
    props: {
      post,
    },
    // ISR - 60 saniyede bir yeniden oluştur
    revalidate: 60,
  };
}

export async function getStaticPaths() {
  const posts = await fetchAllPosts();
  
  return {
    paths: posts.map((post) => ({
      params: { slug: post.slug },
    })),
    // Diğer sayfalar için fallback
    fallback: 'blocking',
  };
}

3. Bundle Optimizasyonu

Webpack Bundle Analyzer

Bundle boyutunu analiz edin:

// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({
  webpack: (config, { isServer }) => {
    // Custom webpack configuration
    if (!isServer) {
      config.resolve.fallback = {
        fs: false,
        net: false,
        tls: false,
      };
    }
    
    return config;
  },
});

Tree Shaking

Kullanılmayan kodu otomatik olarak kaldırın:

// ❌ Tüm lodash kütüphanesini import etme
import _ from 'lodash';

// ✅ Sadece ihtiyacınız olan fonksiyonu import edin
import { debounce } from 'lodash';

// ✅ Daha da iyi: Specific import
import debounce from 'lodash/debounce';

4. Caching Stratejileri

HTTP Caching Headers

Next.js'de caching headers ayarlayın:

// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/api/:path*',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, s-maxage=60, stale-while-revalidate=300',
          },
        ],
      },
      {
        source: '/_next/static/:path*',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=31536000, immutable',
          },
        ],
      },
    ];
  },
};

SWR ile Client-Side Caching

Veri getirme ve caching için SWR kullanın:

import useSWR from 'swr';

const fetcher = (url) => fetch(url).then((res) => res.json());

const UserProfile = ({ userId }) => {
  const { data, error, isLoading } = useSWR(
    `/api/users/${userId}`,
    fetcher,
    {
      revalidateOnFocus: false,
      revalidateOnReconnect: false,
      refreshInterval: 60000, // 1 dakikada bir yenile
    }
  );
  
  if (error) return 
Failed to load
; if (isLoading) return
Loading...
; return
Hello {data.name}!
; };

5. Performance Monitoring

Web Vitals Ölçümü

Core Web Vitals'ı izleyin:

// pages/_app.js
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';

function sendToAnalytics(metric) {
  // Analytics servisinize gönderin
  console.log(metric);
}

export function reportWebVitals(metric) {
  switch (metric.name) {
    case 'CLS':
      getCLS(sendToAnalytics);
      break;
    case 'FID':
      getFID(sendToAnalytics);
      break;
    case 'FCP':
      getFCP(sendToAnalytics);
      break;
    case 'LCP':
      getLCP(sendToAnalytics);
      break;
    case 'TTFB':
      getTTFB(sendToAnalytics);
      break;
    default:
      break;
  }
}

export default function MyApp({ Component, pageProps }) {
  return ;
}

6. Advanced Optimizasyon Teknikleri

Service Workers

Offline caching ve background sync için service workers:

// next.config.js
const withPWA = require('next-pwa')({
  dest: 'public',
  register: true,
  skipWaiting: true,
  runtimeCaching: [
    {
      urlPattern: /^https:\/\/api\.example\.com\/.*/i,
      handler: 'CacheFirst',
      options: {
        cacheName: 'api-cache',
        expiration: {
          maxEntries: 32,
          maxAgeSeconds: 24 * 60 * 60, // 24 hours
        },
      },
    },
  ],
});

module.exports = withPWA({
  // Next.js config
});

Edge Functions

Vercel Edge Functions ile performans artırın:

// pages/api/edge-example.js
export const config = {
  runtime: 'edge',
};

export default async function handler(req) {
  const { searchParams } = new URL(req.url);
  const name = searchParams.get('name') || 'World';
  
  return new Response(
    JSON.stringify({ message: `Hello, ${name}!` }),
    {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'public, s-maxage=60',
      },
    }
  );
}

Sonuç

React ve Next.js performans optimizasyonu, kullanıcı deneyimini iyileştirmek için kritik öneme sahiptir. Bu rehberde ele aldığımız teknikleri uygulayarak:

elde edebilirsiniz. Performans optimizasyonu sürekli bir süreçtir ve düzenli olarak ölçümleme ve iyileştirme yapmanız önemlidir.

React Next.js Performance