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