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

2024年1月29日,開源日報第1089期:
今日推薦開源項目:《just-react》
今日推薦英文原文:《Design Patterns in React: Container vs. Presentational Components, Higher-Order Components (HOC), and Render Props》


開源項目

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

推薦理由: 「React技術揭秘」 一本自頂向下的React源碼分析書,也有web端可供閱讀

網站直達:react.iamkasong.com/


英文原文

今日推薦英文原文:Design Patterns in React: Container vs. Presentational Components, Higher-Order Components (HOC), and Render Props
推薦理由:這篇文章總結了React中的三種設計模式:容器組件、展示組件、高階組件(HOC)和渲染屬性(Render Props),比如文章講容器組件負責管理狀態、發起數據請求和處理業務邏輯,而展示組件專註於純UI渲染等等,選擇適當的模式在React項目其實更為重要


Design Patterns in React: Container vs. Presentational Components, Higher-Order Components (HOC), and Render Props

Intro

React, the popular JavaScript library for building user interfaces, offers developers various design patterns to create organized, maintainable, and reusable code. In this article, we』ll explore three fundamental design patterns in React: Container Components, Presentational Components, Higher-Order Components (HOCs), and Render Props. By understanding these React design patterns and seeing them in action with functional components, you can write more efficient and modular React applications.

Let』s Get Cozy with the Challenge:

As we embark on our React adventure, we understand that keeping your codebase clean and scalable is essential. We face the common challenge of managing state and data flow between components. That』s where our trusty design patterns come into play.

  1. Container vs. Presentational Components:

First, meet the Container Components. They』re like the project managers of your components, responsible for managing state, making data requests, and handling the business logic. You might often see them connecting to Redux stores or other state management solutions.

// Container Component
import React, { useState, useEffect } from 'react';

function UserListContainer() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Fetch user data from an API and update the state
  }, []);

  return <UserList users={users} />;
}

On the other hand, the Presentational Components (our 「dumb」 friends) are pure UI renderers, free from any logic burden. They focus solely on rendering beautiful components and are incredibly reusable.

// Presentational Component
import React from 'react';

function UserList({ users }) {
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

2. Higher-Order Components (HOCs):

Now, say hello to our dynamic Higher-Order Components (HOCs). They』re like the cool utility belt for your components. HOCs are functions that take a component and return an enhanced one. They can add extra props, work with lifecycles, or encapsulate common functions. Imagine them as your go-to superpowers to handle authentication or data fetching for any component.

// Higher-Order Component
import React from 'react';

function withAuthentication(WrappedComponent) {
  return function WithAuthentication(props) {
    // Add authentication logic here

    return <WrappedComponent {...props} />;
  };
}

// Usage
const AuthenticatedComponent = withAuthentication(MyComponent);

3. Render Props:

And finally, let』s meet the versatile Render Props. They』re the chameleons of React. With Render Props, you pass a function as a prop to a component, allowing it to render some of its logic using that function. This is perfect when you need to share complex rendering logic. It』s like inviting your talented friend to jazz up your component.

// Render Props
import React, { useState } from 'react';

function MouseTracker({ render }) {
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });

  function handleMouseMove(event) {
    setMousePosition({ x: event.clientX, y: event.clientY });
  }

  return (
    <div onMouseMove={handleMouseMove}>
      {render(mousePosition)}
    </div>
  );
}

const App = () => (
  <MouseTracker
    render={({ x, y }) => (
      <p>
        Mouse position: {x}, {y}
      </p>
    )}
  />
);

Choosing the Right Pattern:

The choice between these patterns depends on your specific use case. In most of the cases use Container Components when you need to manage state and data flow, Presentational Components for purely rendering UI, Higher-Order Components for cross-cutting concerns, and Render Props when you need to share complex rendering behavior.

By now, you』re probably itching to try out these friendly patterns in your React projects. With their help, you』ll enjoy a cleaner, more scalable, and better-organized codebase. No more code confusion!

Conclusion

Design patterns in React, including Container vs. Presentational Components, Higher-Order Components, and Render Props, are your secret sauce for solving common challenges in building React applications. Whether you prefer dynamic HOCs or versatile Render Props, these patterns are here to make your React coding experience enjoyable. So, keep experimenting, keep learning, and keep coding! Your journey to becoming a React pro has just become a lot friendlier. Happy coding! 🎉


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