ตัวอย่างการใช้ Redux ในการจัดการ state ในโปรเจค React
Redux เป็นไลบรารีสำหรับจัดการ state (state management)
-
Single source of truth: State ของทั้งแอปพลิเคชันจะถูกเก็บไว้ใน object เดียวกัน ที่เรียกว่า store ซึ่งเป็น state tree
-
State is read-only: ไม่สามารถแก้ไข state โดยตรงได้ การเปลี่ยนแปลง state จะต้องผ่าน actions ที่ส่งเข้าไปยัง reducers เพื่ออัปเดต state
-
Changes are made with pure functions: Reducer เป็นเพียง pure functions ที่รับ
previous state
และaction
แล้ว returnnext state
ใน Reducer เราสามารถเปลี่ยน state ได้ โดยการ returnnew state
ไม่ใช่การแก้ไข state เดิม (mutating the previous state
)
- Store: เก็บ state ของแอปพลิเคชันทั้งหมดอยู่ในที่เดียวกัน ซึ่งเป็น state tree ที่ไม่สามารถเปลี่ยนแปลงได้โดยตรงจากภายนอก
- Actions: หน้าที่ของ Action คือ เป็นตัวบอกว่าข้อมูลนั้นคืออะไร จะทําอะไรกับมัน
- Reducers: รับ Actions และแปลง state ของแอปพลิเคชันใน Store ตาม Actions ที่ถูกเรียก
- Dispatch: เป็นการส่ง Actions ไปยัง Reducers เพื่อทำการเปลี่ยนแปลง state ของ Store
เมื่อ Actions ถูกส่งไปยัง Reducers แล้ว จะเกิดการอัปเดต stateใน Store และนำ state ใหม่นี้ไปแสดงผลในส่วนต่าง ๆ ของแอปพลิเคชัน
- Clone the repository:
git clone https://github.com/fakfa19/react-redux.git
- Install dependencies:
cd react-redux
npm install
To start the development server, run:
npm start
This will start the application in development mode. Open http://localhost:3000 to view it in the browser.
src/
|-- actions/
| |-- couterAction.ts
| |-- index.ts
|-- reducers/
| |-- counterReducer.ts
| |-- index.ts
|-- store/
| |-- index.ts
|-- App.tsx
|-- index.tsx