React 애플리케이션 최적화

PHPz
풀어 주다: 2024-09-08 20:30:31
원래의
439명이 탐색했습니다.

Optimize React Application

React 애플리케이션을 최적화하려면 성능, 번들 크기 감소, 효율적인 렌더링 및 전반적인 사용자 경험에 초점을 맞춘 몇 가지 주요 전략을 사용할 수 있습니다. React와 관련된 최적화 기술은 다음과 같습니다.

1. 코드 분할

코드 분할을 사용하면 전체 애플리케이션을 한 번에 로드하는 대신 필요에 따라 로드할 수 있는 작은 단위로 앱을 나눌 수 있습니다. 이렇게 하면 초기 로드 시간이 향상됩니다.

  • React.lazy: React에 내장된 지연 로딩 기능을 사용하여 구성 요소를 동적으로 가져옵니다.
  const LazyComponent = React.lazy(() => import('./Component'));

  function App() {
    return (
      <react.suspense fallback="{<div">Loading...}>
        <lazycomponent></lazycomponent>
      </react.suspense>
    );
  }
로그인 후 복사
  • React Loadable: 또는 react-loadable과 같은 라이브러리를 사용하여 고급 코드 분할 옵션을 사용할 수 있습니다.

2. 메모화 및 불필요한 재렌더링 방지

React 애플리케이션의 성능을 향상하려면 불필요한 재렌더링을 피하는 것이 중요합니다.

  • React.memo: 기능적 구성요소를 React.memo로 래핑하여 props가 변경되지 않은 경우 다시 렌더링되는 것을 방지합니다.
  const MyComponent = React.memo(({ value }) => {
    return <div>{value}</div>;
  });
로그인 후 복사
  • useMemo: 비용이 많이 드는 계산을 메모하여 필요한 경우가 아니면 렌더링할 때마다 다시 계산되지 않도록 합니다.
  const computedValue = useMemo(() => expensiveComputation(value), [value]);
로그인 후 복사
  • useCallback: 특히 하위 구성 요소나 효과에서 종속성으로 사용될 때 매번 새로운 참조가 전달되지 않도록 함수를 메모합니다.
  const handleClick = useCallback(() => {
    console.log('Clicked');
  }, []);
로그인 후 복사

3. 효율적인 상태 관리 사용

불필요한 렌더링을 방지하는 방식으로 상태를 처리하면 성능이 크게 향상될 수 있습니다.

  • useReducer: 복잡한 상태 로직의 경우 상태 변경을 더 효과적으로 제어하려면 useState 대신 useReducer를 사용하는 것이 좋습니다.
  const [state, dispatch] = useReducer(reducer, initialState);
로그인 후 복사
  • 컴포넌트 분할: 상태가 변경될 때 필요한 부분만 다시 렌더링되도록 구성 요소를 분할합니다.

4. 긴 목록 가상화

긴 목록이나 테이블을 렌더링하면 성능이 저하될 수 있습니다. 목록 가상화 기술을 사용하여 화면에 보이는 것만 렌더링하세요.

  • react-window 또는 react-virtualized: 이 라이브러리를 사용하면 목록을 가상화하여 대규모 데이터 세트를 효율적으로 렌더링할 수 있습니다.
  import { FixedSizeList as List } from 'react-window';

  const MyList = ({ items }) => (
    <list height="{500}" itemcount="{items.length}" itemsize="{35}" width="{300}">
      {({ index, style }) => <div style="{style}">{items[index]}</div>}
    </list>
  );
로그인 후 복사

5. 나무 흔들기

애플리케이션이 번들 크기를 줄이는 데 사용되는 라이브러리 부분만 가져왔는지 확인하세요.

  • ES6 가져오기: 전체 라이브러리가 아닌 라이브러리(예: lodash, moment.js 등)에서 필요한 모듈만 가져옵니다.
  // Instead of this:
  import _ from 'lodash';

  // Do this:
  import debounce from 'lodash/debounce';
로그인 후 복사

6. 지연 로드 이미지

이미지는 페이지에서 가장 큰 자산인 경우가 많습니다. 지연 로딩을 사용하면 이미지가 뷰포트에 나타날 때까지 이미지 로딩을 지연할 수 있습니다.

  • react-lazyload: 이미지를 간단하게 지연 로딩하려면 react-lazyload 라이브러리를 사용하세요.
  import LazyLoad from 'react-lazyload';

  const ImageComponent = () => (
    <lazyload height="{200}" once>
      <img src="image-url.jpg" alt="React 애플리케이션 최적화">
    </lazyload>
  );
로그인 후 복사
  • 교차로 관찰자: 교차로 관찰자 API를 사용하여 이미지가 표시될 때 느리게 로드할 수도 있습니다.
  const LazyImage = ({ src, alt }) => {
    const [inView, setInView] = useState(false);
    const imgRef = useRef(null);

    useEffect(() => {
      const observer = new IntersectionObserver(([entry]) => {
        if (entry.isIntersecting) {
          setInView(true);
          observer.disconnect();
        }
      });
      observer.observe(imgRef.current);
    }, []);

    return <img ref="{imgRef}" src="%7BinView" : alt="{alt}">;
  };
로그인 후 복사

7. 자바스크립트 축소

  • 빌드 프로세스 중에 JavaScript 번들의 크기를 줄이려면 Terser 또는 Webpack에 내장된 축소 기능을 사용하세요.

  • Create React App은 프로덕션 빌드를 위한 코드를 자동으로 축소합니다.

  npm run build
로그인 후 복사

8. 번들 분석

JavaScript 번들의 크기를 분석하여 개선할 수 있는 영역을 식별하세요.

  • webpack-bundle-analyzer를 사용하여 번들을 시각화하고 어떤 라이브러리가 가장 많은 공간을 차지하고 있는지 확인하세요.
  npm install --save-dev webpack-bundle-analyzer
로그인 후 복사

Webpack 구성에서:

  const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
  module.exports = {
    plugins: [
      new BundleAnalyzerPlugin()
    ]
  };
로그인 후 복사

9. 사용하지 않는 CSS 줄이기

  • PurgeCSS와 같은 도구를 사용하여 번들에서 사용하지 않는 CSS를 제거하세요. 이를 Webpack 또는 PostCSS 구성과 통합할 수 있습니다.
  npm install @fullhuman/postcss-purgecss
로그인 후 복사

PostCSS 구성 예:

  const purgecss = require('@fullhuman/postcss-purgecss')({
    content: ['./src/**/*.js', './public/index.html'],
    defaultExtractor: content => content.match(/[\w-/:]+(?



<h3>
  
  
  10. <strong>네트워크 요청 최적화</strong>
</h3>

<p>네트워크 요청 수를 줄이고 API 호출을 최적화하면 성능이 크게 향상될 수 있습니다.</p>

로그인 후 복사
  • Debouncing API Calls: Use debouncing to limit how often API requests are sent during user input.
  const fetchResults = debounce((query) => {
    // API call logic
  }, 300);
로그인 후 복사
  • Caching API Data: Use libraries like SWR or React Query to cache API requests and avoid refetching data unnecessarily.
  import useSWR from 'swr';

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

  const MyComponent = () => {
    const { data, error } = useSWR('/api/data', fetcher);

    if (error) return <div>Error loading data</div>;
    if (!data) return <div>Loading...</div>;
    return <div>{data.message}</div>;
  };
로그인 후 복사

11. Use React Fragments

Avoid adding unnecessary elements to the DOM by using React Fragments ( and >) when wrapping multiple elements.

const MyComponent = () => (
  
    <h1>Title</h1>
    <p>Content</p>
  >
);
로그인 후 복사

12. Profiling and Performance Testing

Use the React Developer Tools profiler to identify performance bottlenecks in your app.

  • React Profiler: In Chrome or Firefox, open the React DevTools and switch to the "Profiler" tab. Record a session and analyze where components are re-rendering and consuming more time.

Conclusion

Optimizing a React application requires careful attention to performance, bundle size, and rendering efficiency. By employing techniques like code splitting, memoization, lazy loading, tree shaking, and minimizing network requests, you can significantly improve the performance of your app. Make sure to regularly analyze and test your app’s performance to catch any potential inefficiencies.

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

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