Performance optimization recommendations
Component development standards and performance optimization are essential aspects of front-end engineering. Proper standards and optimization techniques can enhance code quality, maintainability, and runtime efficiency while reducing maintenance costs.
Component Development Standards
Naming Conventions
Component names should use PascalCase and match the file name. For example:
// Button.jsx
function Button() {
return <button>Click</button>;
}
// IconButton.jsx
function IconButton() {
return <button>🔔</button>;
}
Directory Structure
Organize components by functionality:
components/
├── common/ # Common components
│ ├── Button/
│ │ ├── index.jsx
│ │ ├── style.module.css
│ │ └── test.js
├── features/ # Business components
│ ├── UserCard/
│ │ ├── index.jsx
│ │ └── hooks.js
Props Design
- Use PropTypes or TypeScript to define types.
- Keep props flat and avoid deep nesting.
- Set reasonable default values for commonly used props.
interface CardProps {
title: string;
size?: 'sm' | 'md' | 'lg';
onClick?: () => void;
}
function Card({ title, size = 'md', onClick }: CardProps) {
// ...
}
State Management
- Prefer
useState
for internal component state. - Extract complex state logic into custom Hooks.
- Avoid directly using global state in components.
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => setValue(v => !v), []);
return [value, toggle];
}
function Switch() {
const [on, toggle] = useToggle();
return <button onClick={toggle}>{on ? 'ON' : 'OFF'}</button>;
}
Performance Optimization Recommendations
Rendering Optimization
- Use
React.memo
to avoid unnecessary re-renders. - Use
useMemo
/useCallback
wisely to cache computed values. - Always add
key
props to list items.
const ExpensiveComponent = React.memo(function({ data }) {
// Only re-renders when data changes
return <div>{expensiveCalculation(data)}</div>;
});
function List({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
Resource Loading
- Implement code splitting for on-demand loading.
- Use lazy loading for images.
- Preload critical resources.
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<Spinner />}>
<LazyComponent />
</Suspense>
);
}
Memory Management
- Clean up event listeners promptly.
- Avoid memory leaks.
- Use virtual lists for large datasets.
function ScrollListener() {
useEffect(() => {
const handleScroll = () => {
console.log(window.scrollY);
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
}
CSS Optimization
- Avoid deeply nested selectors.
- Use CSS Modules or styled-components.
- Minimize reflows and repaints.
/* Avoid */
.container .list .item .icon {
color: red;
}
/* Recommended */
.itemIcon {
color: red;
}
Build Optimization
- Use Tree Shaking to remove unused code.
- Minify and obfuscate code.
- Configure
splitChunks
appropriately.
// webpack.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
},
},
},
},
};
Performance Monitoring and Analysis
Performance Metrics
- Use the Performance API to measure key metrics.
- Monitor First Contentful Paint (FCP).
- Track Largest Contentful Paint (LCP).
// Measure function execution time
function measure() {
performance.mark('start');
// Execute code
performance.mark('end');
performance.measure('measure', 'start', 'end');
const duration = performance.getEntriesByName('measure')[0].duration;
console.log(`Execution time: ${duration}ms`);
}
Chrome DevTools Tips
- Use the Performance panel to record runtime performance.
- Analyze memory usage with the Memory panel.
- Check code coverage with the Coverage panel.
// Manually trigger garbage collection (debugging only)
if (window.gc) {
window.gc();
}
Real User Monitoring (RUM)
- Collect metrics like FP, FCP, and LCP.
- Track JavaScript errors.
- Monitor API request performance.
// Report performance data
function reportPerf() {
const timing = window.performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
navigator.sendBeacon('/analytics', { loadTime });
}
window.addEventListener('load', reportPerf);
Solutions to Common Performance Issues
Long List Rendering
- Use virtual scrolling techniques.
- Implement pagination.
- Reduce DOM node count.
import { FixedSizeList as List } from 'react-window';
function BigList({ items }) {
return (
<List
height={500}
itemCount={items.length}
itemSize={50}
width="100%"
>
{({ index, style }) => (
<div style={style}>{items[index]}</div>
)}
</List>
);
}
Animation Performance
- Use
transform
andopacity
properties. - Enable GPU acceleration.
- Avoid JavaScript in animations.
/* High-performance animations */
.box {
transition: transform 0.3s ease;
will-change: transform;
}
.box:hover {
transform: scale(1.1);
}
High-Frequency Event Handling
- Use debouncing/throttling.
- Use passive event listeners.
- Avoid heavy operations in event handlers.
// Throttle implementation
function throttle(fn, delay) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn.apply(this, args);
}
};
}
window.addEventListener('scroll', throttle(handleScroll, 100));
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
下一篇:可访问性要求