+1

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

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, detecting vulnerabilities, 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 Concerns of the project and Solutions?"
  • "What are 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. Testing Tools

Popular ways to test React projects nowadays include:

  1. Jest: A widely used testing framework for JavaScript, including React. Jest provides a comprehensive environment for unit testing, snapshot testing, and mocking, making it ideal for both synchronous and asynchronous testing.

  2. React Testing Library (RTL): Built on top of Jest, RTL focuses on testing component behavior over implementation details by simulating user interactions and testing the rendered output. RTL emphasizes accessibility and works well for integration tests by emulating real user actions.

  3. Vitest: Fast and integrated, designed to work seamlessly with Vite, it offers faster test runs and hot module replacement (HMR), making it ideal for projects using Vite for development, Vitest shares a similar API with Jest, making it easy for developers familiar with Jest to transition, as it supports features like expect and describe. Supports mocking out of the box, which is convenient for isolating components and dependencies in tests.

  4. Cypress: A popular end-to-end testing tool for React that provides a real browser environment. Cypress is used for testing user flows across the application, focusing on UI behavior in a real-world scenario.

  5. Playwright: Known for its cross-browser testing capabilities, Playwright is increasingly popular for end-to-end testing, allowing developers to automate and verify app behavior across different browser environments.

  6. Storybook with Chromatic: Storybook allows React components to be visually tested in isolation, while Chromatic enables automated visual regression tests, ensuring the UI doesn’t change unexpectedly.

These tools allow for a well-rounded approach to testing React applications, from unit tests with Jest and RTL to end-to-end tests with Cypress and Playwright, making them effective for robust, production-ready apps.

5. 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! 😃


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí