⚡🚀 Quickly Understand Existing React Projects (or any Others) Using Github Copilot 🤖

0 0 0

Người đăng: Truong Phung

Theo Viblo Asia

A. Github Copilot

When joining a large React project (or other type of projects that've been built for years), Copilot can help answer questions to rapidly grasp the project and support refatoring, generate new code snippets based on prompts (If you're not familiar with Copilot, I highly recommend you to take a look at this awesome course LINK).

Following are some important questions to quickly gain an understanding of the project's structure and critical components... , remember to prefix all below questions with @workspace so Github Copilot can get enough context to provide best possible answers.

@workspace What are the main folders, and what does each one contain?

1. Important Questions

  1. Project Structure & Dependencies
  • “What are the main folders, and what does each one contain?”
  • “Is the project organized by layers (e.g., components, services, utils) or by features (e.g., auth, user, product)?”
  • “What are the major dependencies in package.json, and how do they impact the project?”
  1. State Management & Data Flow
  • “What state management library is being used (e.g., Redux, Context API, Zustand)?”
  • “How is global state organized and accessed throughout the app?”
  1. API Integration
  • "What libraries and approache are being used to handle API calls ?"
  • “Where are API calls being handled, and is there a service layer?”
  • “How are API errors handled?”
  1. Routing & Navigation
  • “What routing library is being used, and what does the route structure look like?”
  • “Is there any code-splitting or lazy-loading implemented in routes?”
  1. UI Components & Styling
  • “How are styles managed (CSS modules, styled-components, Tailwind, etc.)?”
  • “Where are the shared UI components located, and are they documented?”
  1. Code Quality
  • "What are linting configurations? are there any custom rules?"
  • “Is Prettier being used, and what is the configuration for code formatting?”
  • “Are linting and formatting checks integrated into CI/CD?”
  1. Testing
  • “What testing frameworks are set up (e.g., Jest, React Testing Library, Vitest, Cypress...)?”
  • “Are there any specific patterns or structures for writing tests?”
  1. Build & Deployment
  • “What build tool and configuration are used (Webpack "Create-React-App", Vite, etc.)?”
  • “What environments are defined, and how is deployment handled?”
  1. Other Questions (Optional)
  • "What are Vulnerabilities, Security, Performance Concerns of the project and Solutions?"
  • "What are design patterns are being used in the project?"
  • "How to refactor from using CRA to Vite?"
  • "Share ideas to turn project from monolith to microservices?"

These questions will help provide an overview, and you can ask Copilot for code snippets and information on each section.

2. Useful tips with Copilot

  1. Directing inline code susgestions by code comments
    // Register Form with Username, Email, Password and Error Handling
    // ... <Write something to get relevant code susgestion>
    // Input validator for password, password must be at least 8 characters, 1 number, 1 uppercase letter, 1 special character 
    //...
    
  2. Quickly generate meaningful commit message for git commit.
  • Simply click on star icon on Source Control View in VSCode to get relevant commit message.
  1. Use #selection, #terminalSelection to avoid flooding Chat View.
  • Instead of copy pasting all working code snipped, command message for analyzing, overtime it could flood ChatView, we should use Selection Tag for those scenario.
    @workspace #selection add testing
    @workspace #terminalSelection explain the issue
    
  1. Genrate Docs, Tests & Editor Inline Chat
    Code Selection > Copilot > Generate Docs
    Code Selection > Copilot > Generate Tests
    Code Selection > Copilot > Editor Inline Chat
    
  2. Ask for certain terminal command
    @terminal git command to restore all staged files
    
  3. Easily configuring VSCode
  • We can ask anything regarding configuring VSCode
    @vscode change to light theme
    @vscode what are common useful pluggins for React Projects
    @vscode reset UI to default
    
  1. Use multiple Chat Views for differect working sessions, purposes
  • On top of Chat View, we can click + button to open new Chat for new working session, thus to avoid flooding Chat View overtime, and we can easily check previous Chat (past conversations) by clicking on History Button on top of Chat View

B. Important Aspects of React Apps (Appendix)

1. Styling Approach

The most popular and widely adopted ways to style React applications include several distinct approaches. Here’s a breakdown of the top techniques:

  1. CSS Modules: This approach allows scoping of CSS to individual components by generating unique class names, which helps prevent style conflicts across the application. CSS Modules are beneficial for maintaining modularity and are especially effective in larger applications where global scope might become problematic.

  2. CSS-in-JS: Libraries like Styled Components and Emotion are popular for enabling CSS to be written directly in JavaScript. They allow developers to create encapsulated styles within components, providing flexibility for dynamic styling based on component props and states. Styled Components, for example, can simplify theme management and ensure that styles are tightly coupled with components, which can improve maintainability.

  3. Utility-first CSS Frameworks: Tailwind CSS remains a favorite for utility-based styling, enabling developers to apply classes directly in JSX. This approach speeds up development and ensures consistency, although it may result in "class overload" in HTML if overused. Tailwind is also highly customizable through a configuration file, which allows tailored designs for specific applications.

  4. Component Libraries: Solutions like Material UI, Chakra UI, and Ant Design provide pre-styled, accessible, and customizable components. These libraries are ideal for quickly building interfaces with consistent design patterns, offering a balance between functionality and ease of styling, though they may add dependency overhead.

Each of these methods has its advantages and potential drawbacks depending on project needs, team preferences, and scalability considerations. Combining these techniques can sometimes lead to optimal results, like using CSS Modules for core styles and Tailwind for utility-based customizations.

2. State Management

In React applications, state management organizes and manages application data, helping components access and synchronize data seamlessly. Here are some common state management approaches in React:

  1. Local Component State
  • Managed directly within components using useState and useReducer hooks.
  • Ideal for data that doesn’t need to be shared across multiple components, like form input or toggles.
  1. Context API
  • React's built-in way to provide and consume global state across components without prop-drilling.
  • Best suited for lighter applications or for global settings like theme toggles or user authentication status.
  • Uses createContext and useContext hooks for sharing and accessing state.
  1. Third-Party State Management Libraries
  • Redux: A widely-used library with a strict, centralized state model that supports asynchronous actions. Redux is often used with redux-thunk or redux-saga for handling async actions.
  • Zustand: A lighter, simpler alternative to Redux with a minimalistic API, ideal for simpler applications needing shared state.
  • MobX: Manages state using observable values and has a less strict structure than Redux, making it more flexible for certain applications.
  • Recoil: Developed by Facebook for React applications, it simplifies managing complex shared state across multiple components.
  1. React Query and Other Data Fetching Libraries
  • React Query (now called TanStack Query): Optimizes data fetching, caching, and synchronization. It's not exactly for managing application state but works well for managing server state.
  • SWR: Developed by Vercel, SWR focuses on data fetching and caching to reduce network requests, improving app performance.
  1. Jotai and XState
  • Jotai: A lightweight atomic state management library that treats each piece of state as an independent atom.
  • XState: Manages state using state machines and statecharts, suitable for complex applications with multiple states and transitions.

These approaches each have unique advantages, with the best choice depending on the complexity and scale of the application. In many projects, a combination of these tools is used to balance simplicity, performance, and maintainability.

3. Build Tools

React build tools are essential for transforming and optimizing your React application for deployment. Here are some common tools and their roles:

  1. Webpack
  • Bundling: Combines JavaScript files into a single bundle for faster loading.
  • Transpilation: Works with Babel to convert modern JavaScript (e.g., JSX and ES6+) into a format compatible with all browsers.
  • Code Splitting: Enables loading only essential code, reducing initial load times.
  • Plugins & Loaders: Extensive plugins allow additional tasks like asset compression and environment setup.
  1. Babel
  • Transpiler: Transforms newer JavaScript (ES6+) and JSX into compatible code for older browsers.
  • Plugins and Presets: Support for plugins to enable language features (e.g., JSX, TypeScript) and optimization.
  1. Vite
  • Development-Focused: Provides instant hot module reloading and minimal config for rapid dev workflows.
  • Ecosystem: Integrates well with ES modules (use the import and export syntax to manage dependencies and enable code splitting), allowing faster builds by only reloading changed modules.
  • Build Efficiency: Optimized for bundling, making it increasingly popular in the React ecosystem.
  1. Parcel
  • Zero-Configuration: Automatically handles HTML, CSS, and JavaScript bundling without config.
  • Fast Builds: Efficient development experience with caching and fast rebuilds.
  • Code Splitting and Tree Shaking: Supports essential optimizations for reduced bundle size.
  1. Create React App (CRA)
  • All-in-One Tool: Sets up a new React project with pre-configured Webpack, Babel, and ESLint.
  • Customization: Though opinionated, CRA allows "ejecting" to gain full control over the Webpack config if needed.

Currently, Vite is gaining popularity as the go-to build tool for React applications. Here's why:

  1. Faster Development Experience: Vite's optimized for development with instant hot module replacement (HMR), allowing faster reloading compared to Webpack, especially in large projects. Vite accomplishes this by using native ES modules, which only reload modified modules, enhancing efficiency.

  2. Simplicity and Minimal Configuration: Unlike Webpack, which can require extensive configuration, Vite is mostly configuration-free out of the box, especially appealing for rapid prototyping and small to medium projects.

  3. Optimized for Modern Bundling: While Webpack remains widely used and powerful, especially for complex configurations, Vite's approach to bundling with tools like Rollup results in faster, more streamlined production builds.

  4. Compatibility with React Ecosystem: Vite’s ecosystem now supports React and various CSS frameworks, along with popular libraries, making it an attractive, low-friction choice for new React projects.

Webpack remains popular, especially in enterprise settings and for projects with complex bundling needs, but Vite’s speed and simplicity are making it a popular choice for developers prioritizing fast iteration.

4. ReactJs vs NextJs

ReactJS is a library for building user interfaces, focusing solely on the frontend to create interactive UIs, manage component states, and handle UI rendering efficiently. It requires additional libraries and tools to enable server-side rendering (SSR) and routing, as it’s limited to client-side functionality.

Next.js, built on top of React, is a complete framework designed for React applications, adding key features that support server-side rendering, static site generation (SSG), and serverless functions out of the box. It simplifies routing with file-based routing and includes optimizations for performance and SEO, making it a popular choice for full-featured React applications that need SSR or SSG and dynamic page loading.

In summary:

  • ReactJS: A JavaScript library focused on client-side UI development.
  • Next.js: A React-based framework with built-in SSR, SSG, routing, and more, suitable for SEO-driven and full-stack applications.

If you found this helpful, let me know by leaving a 👍 or a comment!, or if you think this post could help someone, feel free to share it! Thank you very much! 😃

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 525

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 433

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 153

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 145

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 110

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 245