開源日報每天推薦一個 GitHub 優質開源項目和一篇精選英文科技或編程文章原文,堅持閱讀《開源日報》,保持每日學習的好習慣。

2024年2月25日,開源日報第1116期:
今日推薦開源項目:《search_with_lepton》
今日推薦英文原文:《10 Expert Performance Tips Every Senior JS React Developer Should Know》


開源項目

今日推薦開源項目:《search_with_lepton》傳送門:項目鏈接

推薦理由:與LLM—Continue一起協同編程最簡單的辦法,該插件已發布至VS Code and JetBrains,可以通過使用代理伺服器免費嘗試Continue,該代理伺服器安全地使用我們的API密鑰與GPT-4、Gemini Pro和Phind CodeLlama等模型進行通信,這些模型分別通過OpenAI、Google和Together

直達鏈接: continue.dev/docs


英文原文

今日推薦英文原文:10 Expert Performance Tips Every Senior JS React Developer Should Know

推薦理由:關於提高 JavaScript React 項目性能的 10 個 的總結,涵蓋了高效組件渲染、React.memo 和 PureComponent 的使用、以及使用瀏覽器開發工具和bundle分析來識別和優化性能問題等方面的內容。有代碼示例和詳細解釋


10 Expert Performance Tips Every Senior JS React Developer Should Know

As a senior Javascript React developer, consistently improving the performance of your applications is an essential skill to master. We』ve gathered the top 10 expert performance tips that will elevate your React development game.

img

Let』s take a deep dive into these advanced techniques, illustrated with code examples, and supercharge your React skills!

Efficient Component Rendering

Efficient component rendering is fundamental for top-notch React applications. In this section, we』ll cover various strategies to optimize render performance and help ensure lightning-fast page loads.

React.memo and PureComponents

React.memo and PureComponent are powerful techniques to prevent unnecessary component re-renders. React.memo is a higher-order component for functional components, while PureComponent is a base class for class components. Both optimize the rendering process by only allowing re-renders when the component』s props have shallowly changed.

Let』s compare a regular component with one using React.memo:

// Regular functional component
const TitleRegular = ({ text }) => {
  console.log("Rendering Regular Title...");
  return <h2>{text}</h2>;
};
// Memoized functional component using React.memo
const TitleMemoized = React.memo(({ text }) => {
  console.log("Rendering Memoized Title...");
  return <h2>{text}</h2>;
});

By wrapping our functional component with React.memo, we prevent excessive re-renders and boost performance. However, use these techniques wisely and only when necessary, as they can be counterproductive if applied indiscriminately.

Production Builds:

Ensure your Webpack configuration is set to production mode to enable optimizations like code minification and dead code elimination.

// webpack.config.js
module.exports = {
  mode: 'production',
  // other configurations...
};

Code Splitting:

Implement code splitting using React.lazy() and Suspense to load only the necessary code for each view, reducing initial load times.

const MyLazyComponent = React.lazy(() => import('./MyLazyComponent'));function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <MyLazyComponent />
      </Suspense>
    </div>
  );
}

Virtualization:

Implement virtualization techniques, such as react-window, to efficiently render long lists and tables.

import { FixedSizeList } from 'react-window';function VirtualizedList() {
  return (
    <FixedSizeList
      height={400}
      itemCount={1000}
      itemSize={40}
      width={300}
    >
      {({ index, style }) => (
        <div style={style}>Item {index}</div>
      )}
    </FixedSizeList>
  );
}

Optimize Images:

Optimize image assets, serve responsive images, and consider lazy loading to improve initial load performance.

jsxCopy codeconst MyImage = () => (
  <img src="placeholder.jpg" loading="lazy" alt="Lazy Loaded Image" />
);

Server-Side Rendering (SSR):

Consider server-side rendering (e.g., with Next.js) to render React components on the server, improving initial load times and SEO.

// pages/index.js
import React from 'react';const HomePage = () => {
  return (
    <div>
      <h1>Hello, Next.js SSR!</h1>
    </div>
  );
};
export default HomePage;

Web Workers:

Leverage Web Workers to offload CPU-intensive tasks to a separate thread, preventing main thread blocking and enhancing responsiveness.

// worker.js
onmessage = function (e) {
  const result = performHeavyCalculation(e.data);
  postMessage(result);
};
// main.js
const worker = new Worker('worker.js');
worker.onmessage = function (e) {
  console.log('Result:', e.data);
};
worker.postMessage({ /* data for calculation */ });

Browser DevTools:

Utilize React DevTools and browser developer tools for profiling, identifying bottlenecks, and optimizing your application.

import React from 'react';
import { render } from 'react-dom';
import App from './App';// Attach React DevTools
if (process.env.NODE_ENV === 'development') {
  const { devToolsExtension } = window;
  if (typeof devToolsExtension === 'function') {
    devToolsExtension();
  }
}
// Render the application
render(<App />, document.getElementById('root'));

Bundle Analysis:

Regularly analyze your bundle size using tools like Webpack Bundle Analyzer. Identify and eliminate unnecessary dependencies.

# Install the analyzer package
npm install --save-dev webpack-bundle-analyzer# Update npm scripts
"scripts": {
  "analyze": "webpack --profile --json > stats.json && webpack-bundle-analyzer stats.json"
}

These expert tips cover a range of strategies to enhance the performance of your React applications. Apply them judiciously based on your project』s specific needs for optimal results.


Conclusion

That』s all I can think of at the moment. I may add to this article as I think of other things. I hope this helps!


下載開源日報APP:https://openingsource.org/2579/
加入我們:https://openingsource.org/about/join/
關注我們:https://openingsource.org/about/love/