开源日报每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
2023年12月31日,开源日报第1060期:
今日推荐开源项目:《papers-we-love》
今日推荐英文原文:《React Component Architecture for Job Interviews》


开源项目

今日推荐开源项目:《papers-we-love》传送门:项目链接

推荐理由: "Papers We Love"(PWL)是一个聚焦学术计算机科学论文的社区,通过阅读、讨论和学习推广优秀论文, 也可以在Discord讨论PWL相关内容


英文原文

今日推荐英文原文:React Component Architecture for Job Interviews

推荐理由:本文介绍了在React面试中关于组件架构的重要概念和技巧,涵盖组件架构的基本理念,包括文件结构、Atomic Design、容器组件与展示组件的区分等等,还介绍了在构建大型React应用时如何通过高阶组件(HOC)和高阶函数(HOF)来实现代码重用和可扩展性,最后有自定义Hooks来实现可重用逻辑的方法的例子,比较实用


React Component Architecture for Job Interviews

Are you preparing for a React job interview and want to get right the questions on component architecture? In this post, we’ll cover essential concepts and tips related to component architecture in React, along with some examples. By the end, you’ll be well-equipped to tackle component-related questions with confidence. Let’s dive in!

Understanding Component Architecture

Component architecture is a fundamental concept in React development. It involves breaking down your React application into smaller, self-contained building blocks called components. Each component handles a specific functionality or represents a UI element. This approach improves code organization, making the project more scalable and maintainable.

Tips on Organizing Components

File Structure: A clean file structure is essential for managing large React projects. Group related components into folders and use TypeScript .tsx files and .scss for styles. For instance:

src/
  components/
    Header/
      Header.tsx
      Header.scss
    Sidebar/
      Sidebar.tsx
      Sidebar.scss
  pages/
    Home/
      Home.tsx
      Home.scss
    About/
      About.tsx
      About.scss
  App.tsx
  index.tsx

This is just one of many possibilities we can have for file structure. Frameworks like Next.js already provide their own proposal of the file structure, especially for the pages. it's worth taking a look.

Atomic Design: Familiarize yourself with Atomic Design principles to organize components based on complexity and reusability. Start with atoms (e.g., buttons, inputs), then build molecules (e.g., forms), organisms (e.g., complete headers), and finally templates and pages.

Container vs. Presentational Components: Understand the distinction between container and presentational components. Container components handle logic and data manipulation, while presentational components focus solely on visual representation. This promotes code reuse and easier testing.

Scaling Up with Higher-Order Components (HOC) and Higher-Order Functions (HOF)

When building larger React applications, you’ll often encounter the need for code reuse and scalability. Here’s how Higher-Order Components (HOCs) and Higher-Order Functions (HOFs) come to the rescue.

Higher-Order Components (HOC)

HOCs are functions that take a component as input and return an enhanced version of that component. They are widely used for cross-cutting concerns such as authentication or authorization. Let’s see an example:

import React from 'react';

interface WithAuthProps {
  isAuthenticated: boolean;
}

const withAuth = <P extends object>(
  WrappedComponent: React.ComponentType<P & WithAuthProps>
) => {
  return class extends React.Component<P & WithAuthProps> {
    render() {
      if (this.props.isAuthenticated) {
        return <WrappedComponent {...this.props as P} />;
      } else {
        return <p>Please login to access this content.</p>;
      }
    }
  };
};

interface MyComponentProps {
  // Add your component's props here
}

const MyComponent: React.FC<MyComponentProps> = (props) => {
  // Your component logic here
};

const AuthenticatedComponent = withAuth(MyComponent);

Now, AuthenticatedComponent will render MyComponent only if the user is authenticated; otherwise, it displays a message asking the user to log in.

Higher-Order Functions (HOF)

HOFs, on the other hand, are functions that take a function as input and return a new function with extended functionality. They shine when you need to apply similar transformations or filters to different datasets.

const withFilter = <T extends unknown>(
  filterFunction: (data: T) => boolean
) => (data: T[]) => {
  return data.filter(filterFunction);
};

const numbers = [1, 2, 3, 4, 5];
const evenNumbersFilter = (num: number) => num % 2 === 0;
const getEvenNumbers = withFilter<number>(evenNumbersFilter);

const evenNumbers = getEvenNumbers(numbers);
// Output: [2, 4]

Both HOCs and HOFs are essential concepts to grasp for writing scalable and maintainable React applications.

Reusable Logic with Custom Hooks

Custom Hooks offer an elegant solution for organizing and reusing component logic. They enable you to extract logic into reusable functions and improve code readability.

import React, { useState } from 'react';

const useFormInput = (initialValue: string) => {
  const [value, setValue] = useState(initialValue);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  };

  return {
    value,
    onChange: handleChange,
  };
};

const MyFormComponent: React.FC = () => {
  const firstName = useFormInput('');
  const lastName = useFormInput('');

  return (
    <form>
      <input type="text" {...firstName} />
      <input type="text" {...lastName} />
    </form>
  );
};

By using this custom Hook, you can easily add form handling to any component without duplicating the logic.

Conclusion

Congratulations! You’ve now learned the ins and outs of React component architecture and how to apply them to create scalable and maintainable code. Armed with the knowledge of Higher-Order Components (HOCs), Higher-Order Functions (HOFs), and Custom Hooks, you’re well-prepared for React job interviews.

Remember to practice implementing these concepts in real projects, as hands-on experience is the best way to solidify your understanding. Best of luck in your React job interviews, and happy coding! 😄🚀


下载开源日报APP:https://openingsource.org/2579/
加入我们:https://openingsource.org/about/join/
关注我们:https://openingsource.org/about/love/