开源日报每天推荐一个 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/