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ùngiconsvàfontsnằm trong thư mụcassets. -
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
utilschứa các hàm hỗ trợ. -
File
App.jssẽ chứa một component chính làAppvà 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 filemain.jsx(đối với Vite) chỉ dùng để kết nối componentAppvớiindex.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.jsStrict 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
-
xem thêm Keeping Components Pure ↩