Folder Structure

Cách tổ chức thư mục cho ứng dụng React hiệu quả:

  • Hình ảnh (nằm trong folder images) cùng iconsfonts nằm trong thư mục assets.

  • Các file component được đặt tên theo quy ước CamelCase và nằm trong thư mục components.

  • Dữ liệu nằm trong thư mục data.

  • CSS nằm trong thư mục styles.

  • Thư mục utils chứa các hàm hỗ trợ.

  • File App.js sẽ chứa một component chính là App và import các component khác

    // App.js
    import { Components } from "./Components.js"
     
    export const App = () => {
      return (
        <div>
          <Coponents />
        </div>
      )
    }
  • File index.js (đối với CRA) hoặc file main.jsx (đối với Vite) chỉ dùng để kết nối component App với index.html:

    // index.js
    import React from "react"
    import ReactDOM from "react-dom/client"
    import App from "./App.js"
     
    const root = document.getElementById("root")
    ReactDOM.createRoot(root).render(<App />)

Minh họa:

src
|- assets
	|- fonts
	|- icons
	|- images
|- components
|- data
|- styles
|- utils
|- index.js

Strict Mode

Nên sử dụng component StrictMode cho ứng dụng. Component này giúp phát hiện các lỗi tiềm ẩn có trong ứng dụng và chỉ chạy ở môi trường phát triển.

import { StrictMode } from "react"
import ReactDOM from "react-dom/client"
 
const root = document.getElementById("root")
ReactDOM.createRoot(root).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

Khi dùng StrictMode, mỗi component sẽ được chạy hai lần để đảm bảo tính purity của các component1 và giúp chúng ta dễ tìm lỗi hơn.

Ngoài component, updater function và initializer function2 cũng được chạy hai lần. Chỉ có các event handler là chỉ được chạy một lần.

Resources

Footnotes

  1. xem thêm Keeping Components Pure

  2. xem thêm useState