开源日报每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
开源日报第1115期:500行代码构建一个对话搜索引擎 《search_with_lepton》
2024年2月24日,开源日报第1115期:
今日推荐开源项目:《search_with_lepton》
今日推荐英文原文:《Best Practices — Multiple Child Components in React》


开源项目

今日推荐开源项目:《search_with_lepton》传送门:项目链接

推荐理由:使用Lepton AI 构建一个快速的基于对话的搜索演示
直达链接: search.lepton.run

  • LLM的内置支持
  • 搜索引擎的内置支持
  • 定制化的 UI 界面
  • 可共享、缓存的搜索结果

    英文原文

今日推荐英文原文:Best Practices — Multiple Child Components in React

推荐理由:文章探讨在 React 中创建多个子组件的最佳实践。通过将应用程序拆分为较小的、可重用的代码块,可以提高代码的可读性、可维护性和性能。文章强调了组件的模块化、单向数据流动、避免嵌套过深、使用 React Fragments、为列表项提供唯一的键、组件组合以及测试等方面的重要性,以及测试不足以及忽视 React DevTools 等


Best Practices — Multiple Child Components in React

Explore these best practices to build more maintainable, performant, and modular React applications!

React, with its component-based architecture, allows you to build complex user interfaces by composing smaller, reusable pieces of code. When creating multiple child components within a React application, it’s essential to follow best practices to ensure maintainability, performance, and a smooth development process. In this article, we’ll explore the best practices for working with multiple child components in React.

img

Photo by Markus Spiske on Unsplash

Understanding the Need

Before delving into best practices, let’s understand why creating multiple child components is essential in React.

  1. Reusability:
    Dividing your application into smaller components makes it easier to reuse code. When you create components that serve specific purposes, you can use them across different parts of your application.
  2. Maintainability:
    Smaller, focused components are easier to maintain. They follow the Single Responsibility Principle, which states that each component should do one thing and do it well.
  3. Readability:
    Code becomes more readable when you break it down into smaller, understandable pieces. This makes it easier for developers to collaborate and understand the application’s structure.
  4. Performance:
    React’s virtual DOM and reconciliation process optimize updates when components change. Smaller components help React efficiently update the UI by reducing the scope of changes.

Best Practices

Now, let’s explore the best practices for creating and working with multiple child components in React.

1. Component Modularity

Create small, focused components that serve a single purpose.

Each component should have a specific responsibility, making it easier to understand and maintain.
For example, if you’re building a user profile page, break it down into components like UserProfileHeader, UserProfileBio, and UserProfilePosts.

// UserProfileHeader.js
function UserProfileHeader(props) {
  // Component logic
}
// UserProfileBio.js
function UserProfileBio(props) {
  // Component logic
}
// UserProfilePosts.js
function UserProfilePosts(props) {
  // Component logic
}

2. Props and Data Flow

Pass data and props down the component hierarchy, following a unidirectional data flow.

In React, data should flow from parent components to child components through props. This ensures that components are predictable and easy to test.

// ParentComponent.js
function ParentComponent() {
  const data = "Some data";
  return <ChildComponent data={data} />;
}
// ChildComponent.js
function ChildComponent(props) {
  return <div>{props.data}</div>;
}

3. Avoid Component Hell

Avoid creating deeply nested component hierarchies.

Excessive nesting can lead to a complex and hard-to-maintain codebase. When components become deeply nested, it’s challenging to manage state and props effectively. Consider breaking down complex components into smaller ones\.

4. Use React Fragments

When returning multiple elements from a component, use React Fragments (<>...</>) to avoid unnecessary parent elements.

React Fragments allow you to group multiple elements without adding extra nodes to the DOM. This helps keep the DOM clean and improves performance.

function MyComponent() {
  return (
    <>
      <div>Element 1</div>
      <div>Element 2</div>
    </>
  );
}

5. Keys for Lists

When rendering lists of components, provide a unique key prop to each item.

React uses keys to identify list items and efficiently update them. Using unique keys ensures proper rendering and helps avoid issues when reordering or deleting items.

function ListComponent(props) {
  const items = props.items.map((item) => (
    <ListItem key={item.id} item={item} />
  ));
  return <ul>{items}</ul>;
}

6. Component Composition

Compose complex UIs by combining multiple child components.

Instead of creating monolithic components, build your UI by combining smaller, reusable child components. This promotes code reusability and simplifies testing.

function ComplexComponent() {
  return (
    <div>
      <UserProfileHeader />
      <UserProfileBio />
      <UserProfilePosts />
    </div>
  );
}

7. Testing

Write unit tests for individual child components.

Isolate the testing of child components to ensure they work correctly. This simplifies debugging and makes it easier to catch and fix issues early in development.

8. Performance Optimization

Implement performance optimizations like shouldComponentUpdate, PureComponent, or React.memo as needed.

Performance is critical in React applications. Use these techniques to prevent unnecessary renders and improve the overall performance of your components.

Common Pitfalls

While working with multiple child components in React, watch out for common pitfalls:

  1. **Overusing State:

    **Avoid adding state to components that don’t need it. Instead, use props for data flow.

  2. Prop Drilling:
    Passing props through multiple layers of components can become cumbersome. Consider using React Context or state management libraries like Redux for complex data sharing.
  3. Not Using PureComponent or React.memo:
    If your components are re-rendering unnecessarily, consider optimizing with PureComponent or React.memo.
  4. Inadequate Testing:
    Skipping unit tests for child components can lead to undetected bugs. Test each component in isolation.
  5. Ignoring the React DevTools:
    Familiarize yourself with the React DevTools extension for your browser. It provides valuable insights into component hierarchies and performance.

Summary

Creating multiple child components in React follows the principles of modularity, reusability, and maintainability. By adhering to best practices and being aware of common pitfalls, you can build robust and efficient React applications that are easier to develop and maintain.


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/