더 나은 성능을 위해 React 애플리케이션을 최적화하는 필수 기술

WBOY
풀어 주다: 2024-08-07 09:35:50
원래의
1067명이 탐색했습니다.

Essential Techniques to Optimize React Applications for Better Performance

소개

최신 웹 애플리케이션이 점점 더 복잡해짐에 따라 최적의 성능을 보장하는 것이 점점 더 중요해지고 있습니다. 사용자 인터페이스 구축을 위한 인기 있는 JavaScript 라이브러리인 React는 애플리케이션 성능을 향상시키기 위한 다양한 전략을 제공합니다. 소규모 프로젝트에서 작업하든 대규모 애플리케이션에서 작업하든 이러한 최적화 기술을 이해하고 구현하면 로드 시간이 빨라지고 사용자 경험이 원활해지며 리소스를 효율적으로 사용할 수 있습니다.

이 게시물에서는 효율적인 상태 관리 및 재렌더링 최소화부터 코드 분할 및 지연 로딩 활용에 이르기까지 React 애플리케이션을 최적화하는 필수 기술을 살펴보겠습니다. 이러한 전략은 고성능 애플리케이션을 제공하는 데 도움이 될 뿐만 아니라 애플리케이션이 성장함에 따라 확장성과 응답성을 유지하는 데도 도움이 됩니다. 성능을 최적화하여 React 애플리케이션을 최대한 활용하는 방법을 살펴보겠습니다.

1. React.memo 사용: 불필요한 재렌더링 방지

React.memo는 기능적 구성 요소의 불필요한 재렌더링을 방지하는 데 도움이 되는 고차 구성 요소입니다. 구성 요소의 렌더링된 출력을 메모하고 소품이 변경된 경우에만 다시 렌더링하는 방식으로 작동합니다. 이는 특히 자주 렌더링되지만 소품이 자주 변경되지 않는 구성 요소의 경우 성능이 크게 향상될 수 있습니다.

불필요한 재렌더링을 피하기 위해 React.memo를 사용하는 예를 살펴보겠습니다.

import React, { useState } from 'react';

// A functional component that displays a count
const CountDisplay = React.memo(({ count }) => {
  console.log('CountDisplay rendered');
  return <div>Count: {count}</div>;
});

const App = () => {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('');

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <CountDisplay count={count} />

      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type something"
      />
    </div>
  );
};

export default App;
로그인 후 복사
설명
  • "Increment Count" 버튼을 클릭하면 CountDisplay 구성 요소의 count 속성이 변경되므로 다시 렌더링됩니다.
  • 입력 필드에 입력하면 상위 앱 구성 요소가 다시 렌더링되더라도 count 속성이 변경되지 않은 상태로 유지되므로 CountDisplay 구성 요소는 다시 렌더링되지 않습니다.
2. useMemo 및 useCallback Hooks 사용: 비용이 많이 드는 계산을 메모합니다.

React의 useMemo 및 useCallback 후크는 비용이 많이 드는 계산 및 함수를 메모하여 불필요한 재계산 및 재렌더링을 방지하는 데 사용됩니다. 이러한 후크는 특히 복잡한 계산이나 자주 렌더링되는 구성 요소를 처리할 때 React 애플리케이션의 성능을 크게 향상시킬 수 있습니다.

사용메모

useMemo는 값을 기억하는 데 사용되므로 종속성 중 하나가 변경될 때만 다시 계산됩니다.

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

const ExpensiveCalculationComponent = ({ num }) => {
  const expensiveCalculation = (n) => {
    console.log('Calculating...');
    return n * 2; // Simulate an expensive calculation
  };

  const result = useMemo(() => expensiveCalculation(num), [num]);

  return <div>Result: {result}</div>;
};

const App = () => {
  const [num, setNum] = useState(1);
  const [text, setText] = useState('');

  return (
    <div>
      <button onClick={() => setNum(num + 1)}>Increment Number</button>
      <ExpensiveCalculationComponent num={num} />

      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type something"
      />
    </div>
  );
};

export default App;
로그인 후 복사
설명
  • "증분 숫자" 버튼을 클릭하면 비용이 많이 드는 계산이 실행되고 콘솔에 "계산 중..."이 기록됩니다.
  • useMemo 덕분에 입력 필드에 입력해도 값비싼 계산이 실행되지 않습니다.
콜백 사용

useCallback은 함수를 메모하는 데 사용되므로 종속성 중 하나가 변경될 때만 다시 생성됩니다.

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

const Button = React.memo(({ handleClick, label }) => {
  console.log(`Rendering button - ${label}`);
  return <button onClick={handleClick}>{label}</button>;
});

const App = () => {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('');

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

  return (
    <div>
      <Button handleClick={increment} label="Increment Count" />
      <div>Count: {count}</div>

      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type something"
      />
    </div>
  );
};

export default App;
로그인 후 복사
설명
  • "Increment Count" 버튼을 클릭하면 증가 기능이 실행되고 버튼 구성요소가 불필요하게 다시 렌더링되지 않습니다.
  • useCallback 덕분에 입력 필드에 입력해도 Button 구성 요소가 다시 렌더링되지 않습니다.
3. 지연 로딩 및 코드 분할: 구성 요소를 동적으로 로드

지연 로딩 및 코드 분할은 필요할 때만 구성 요소를 로드하여 애플리케이션 성능을 향상시키기 위해 React에서 사용되는 기술입니다. 이렇게 하면 초기 로드 시간이 줄어들고 전반적인 사용자 경험이 향상됩니다.

- React.lazy 및 Suspense를 사용한 지연 로딩

React는 구성요소의 지연 로딩을 가능하게 하는 내장 함수 React.lazy를 제공합니다. 이를 통해 코드를 더 작은 덩어리로 분할하고 요청 시 로드할 수 있습니다.

import React, { Suspense } from 'react';

// Lazy load the component
const MyLazyComponent = React.lazy(() => import('./MayLazyComponent'));

const App = () => {
  return (
    <div>
      <h1>Welcome to My App</h1>

      {/* Suspense component wraps the lazy loaded component */}
      <Suspense fallback={<div>Loading...</div>}>
        <MyLazyComponent />
      </Suspense>
    </div>
  );
};

export default App;
로그인 후 복사
설명
1. 반응.게으른:
  • React.lazy는 LazyComponent를 동적으로 가져오는 데 사용됩니다.
  • import 문은 구성 요소를 확인하는 Promise를 반환합니다.
2. 서스펜스:
  • Suspense 구성 요소는 지연 로드 구성 요소를 래핑하는 데 사용됩니다.
  • 구성요소가 로드되는 동안 표시할 대체 UI(로드 중...)를 제공합니다.
- React.lazy 및 React Router를 사용한 코드 분할

React Router와 함께 지연 로딩 및 코드 분할을 사용하여 경로 구성 요소를 동적으로 로드할 수도 있습니다.

import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

// Lazy load the components
const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));

const App = () => {
  return (
    <Router>
      <div>
        <h1>My App with React Router</h1>

        <Suspense fallback={<div>Loading...</div>}>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
          </Routes>
        </Suspense>
      </div>
    </Router>
  );
};

export default App;
로그인 후 복사
설명
  • 지연 로드 경로 구성 요소:
    React.lazy는 Home 및 About 구성 요소를 동적으로 가져오는 데 사용됩니다.

  • 서스펜스 및 반응 라우터:
    Suspense 구성 요소는 Route 구성 요소가 로드되는 동안 대체 UI를 제공하기 위해 Routes 구성 요소를 래핑합니다.

4. Virtualize Long Lists: Renders only the visible items

Virtualizing long lists in React using libraries like react-window or react-virtualized can significantly improve performance by rendering only the visible items. This technique is essential for handling large datasets efficiently and ensuring a smooth user experience.

Example
import React from 'react';
import { List } from 'react-virtualized';

const rowRenderer = ({ index, key, style }) => (
  <div key={key} style={style}>
    Row {index}
  </div>
);

const App = () => {
  return (
    <List
      width={300}
      height={400}
      rowCount={1000}
      rowHeight={35}
      rowRenderer={rowRenderer}
    />
  );
};

export default App;
로그인 후 복사
5. Debounce & Throttle Events: Limits the frequency of expensive operations

Debouncing and throttling are essential techniques to optimize performance in React applications by controlling the frequency of expensive operations. Debouncing is ideal for events like key presses, while throttling is more suited for continuous events like scrolling or resizing. Using utility libraries like Lodash can simplify the implementation of these techniques.

- Debounce

Debouncing ensures that a function is only executed once after a specified delay has passed since the last time it was invoked. This is particularly useful for events that trigger frequently, such as key presses in a search input field.

Example using Lodash
import React, { useState, useCallback } from 'react';
import debounce from 'lodash/debounce';

const App = () => {
  const [value, setValue] = useState('');

  const handleInputChange = (event) => {
    setValue(event.target.value);
    debouncedSearch(event.target.value);
  };

  const search = (query) => {
    console.log('Searching for:', query);
    // Perform the search operation
  };

  const debouncedSearch = useCallback(debounce(search, 300), []);

  return (
    <div>
      <input type="text" value={value} onChange={handleInputChange} />
    </div>
  );
};

export default App;
로그인 후 복사
- Throttle

Throttling ensures that a function is executed at most once in a specified interval of time. This is useful for events like scrolling or resizing where you want to limit the rate at which the event handler executes.

Example using Lodash
import React, { useEffect } from 'react';
import throttle from 'lodash/throttle';

const App = () => {
  useEffect(() => {
    const handleScroll = throttle(() => {
      console.log('Scrolling...');
      // Perform scroll operation
    }, 200);

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <div style={{ height: '2000px' }}>
      Scroll down to see the effect
    </div>
  );
};

export default App;
로그인 후 복사
6. Optimize Images and Assets: Reduces the load time

Optimizing images and assets involves compressing files, using modern formats, serving responsive images, and implementing lazy loading. By following these techniques, you can significantly reduce load times and improve the performance of your React application.

Use the loading attribute for images to enable native lazy loading or use a React library like react-lazyload.

Example
import React from 'react';
import lazyImage from './lazy-image.webp';

const LazyImage = () => {
  return (
    <div>
      <img
        src={lazyImage}
        alt="Lazy Loaded"
        loading="lazy" // Native lazy loading
        style={{ width: '100%', maxWidth: '300px' }}
      />
    </div>
  );
};

export default LazyImage;
로그인 후 복사
7. Avoid Inline Functions and Object Literals:

Avoiding inline functions and object literals is important for optimizing performance in React applications. By using useCallback to memoize functions and defining objects outside of the render method, you can minimize unnecessary re-renders and improve the efficiency of your components.

Example
// 1. Inline Function

// Problematic Code:
 <button onClick={() => setCount(count + 1)}>Increment</button>

// Optimized Code:
  // Use useCallback to memoize the function
  const handleClick = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

 <button onClick={handleClick}>Increment</button>

// 2. Inline Object Literals

// Problematic Code:
    <div style={{ padding: '20px', backgroundColor: '#f0f0f0' }}>
      <p>Age: {age}</p>
    </div>

// Optimized Code:
    const styles = {
         container: {
             padding: '20px',
             backgroundColor: '#f0f0f0',
        },
    };

    <div style={styles.container}>
      <p>Age: {age}</p>
    </div>
로그인 후 복사
8. Key Attribute in Lists: React identify which items have changed

When rendering lists in React, using the key attribute is crucial for optimal rendering and performance. It helps React identify which items have changed, been added, or removed, allowing for efficient updates to the user interface.

Example without key attribute

In this example, the key attribute is missing from the list items. React will not be able to efficiently track changes in the list, which could lead to performance issues and incorrect rendering.

    <ul>
      {items.map((item) => (
        <li>{item}</li>
      ))}
    </ul>
로그인 후 복사
Example with key attribute as index

In the optimized code, the key attribute is added to each

  • element. The key value should be a unique identifier for each item. In this case, the index of the item is used as the key. However, it's recommended to use a unique identifier (e.g., item.id) if available, as using indices can cause issues if the list items are reordered or changed.

       <ul>
          {items.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
    
    로그인 후 복사
    Example with Unique Identifiers:

    In this example, each list item has a unique id which is used as the key. This approach provides a more reliable way to track items and handle list changes, especially when items are dynamically added, removed, or reordered.

        <ul>
          {items.map((item) => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
    
    로그인 후 복사
    9. Use Production Build:

    Always use the production build for your React app to benefit from optimizations like minification and dead code elimination.

    Build Command: npm run build
    10. Profile and Monitor Performance:

    Profiling and monitoring performance are crucial for ensuring that your React application runs smoothly and efficiently. This involves identifying and addressing performance bottlenecks, ensuring that your application is responsive and performs well under various conditions.

    - Use React Developer Tools

    React Developer Tools is a browser extension that provides powerful tools for profiling and monitoring your React application. It allows you to inspect component hierarchies, analyze component renders, and measure performance.

    - Analyze Performance Metrics

    Use the performance metrics provided by React Developer Tools to identify slow components and unnecessary re-renders. Look for:

    • 렌더링 시간: 각 구성 요소를 렌더링하는 데 걸리는 시간
    • 구성요소 업데이트: 구성요소가 다시 렌더링되는 빈도
    • 상호작용: 사용자 상호작용이 성능에 미치는 영향

    최종 생각

    이러한 최적화 기술을 구현하면 React 애플리케이션의 성능이 크게 향상되어 로드 시간이 빨라지고 상호 작용이 원활해지며 전반적으로 향상된 사용자 경험을 얻을 수 있습니다. 정기적인 프로파일링 및 모니터링과 이러한 기술의 신중한 적용을 통해 React 애플리케이션이 성장함에 따라 성능과 확장성을 유지할 수 있습니다.

    위 내용은 더 나은 성능을 위해 React 애플리케이션을 최적화하는 필수 기술의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

  • 원천:dev.to
    본 웹사이트의 성명
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
    인기 튜토리얼
    더>
    최신 다운로드
    더>
    웹 효과
    웹사이트 소스 코드
    웹사이트 자료
    프론트엔드 템플릿
    회사 소개 부인 성명 Sitemap
    PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!