더 나은 성능을 위해 React 애플리케이션을 최적화하는 필수 기술
소개
최신 웹 애플리케이션이 점점 더 복잡해짐에 따라 최적의 성능을 보장하는 것이 점점 더 중요해지고 있습니다. 사용자 인터페이스 구축을 위한 인기 있는 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
<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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

Console.log 출력의 차이의 근본 원인에 대한 심층적 인 논의. 이 기사에서는 Console.log 함수의 출력 결과의 차이점을 코드에서 분석하고 그에 따른 이유를 설명합니다. � ...
