// ServerStateComponent.jsimport React from 'react';
export default function ServerStateComponent() { // <mark>Giả lập state phía server</mark> let serverState = { user: 'John Doe', role: 'admin' };
return ( <> <h1>User Information (Server Side)</h1> <p>Name: {serverState.user}</p> <p>Role: {serverState.role}</p> </> );}
serverState
mô phỏng dữ liệu được lưu và quản lý tại server. Component sẽ render trực tiếp dựa trên dữ liệu đó, đảm bảo nội dung động luôn được hiển thị chính xác dựa trên trạng thái trên server.// UpdateUserComponent.jsimport React, { useState } from 'react';
export default function UpdateUserComponent() { const [user, setUser] = useState('');
const handleChange = (e) => { setUser(e.target.value); };
const handleSubmit = async (e) => { e.preventDefault();
// Giả lập cập nhật state phía server console.log(`User updated to: ${user}`);
// Trong thực tế: Gửi thông tin lên server qua API };
return ( <form onSubmit={handleSubmit}> <label> Update User: <input type="text" value={user} onChange={handleChange} /> </label> <button type="submit">Submit</button> </form> );}
handleSubmit
sẽ gọi API hoặc xử lý tại server để cập nhật dữ liệu tương ứng, đảm bảo sự đồng bộ state từ client đến server.App.js
để đồng bộ và hiển thị dữ liệu.// App.jsimport React, { useState, useEffect } from 'react';import ServerStateComponent from './ServerStateComponent';import UpdateUserComponent from './UpdateUserComponent';
function App() { const [serverState, setServerState] = useState({ user: '', role: '' });
useEffect(() => { const fetchServerState = async () => { // Giả lập gọi server lấy state hiện tại const state = { user: 'Jane Doe', role: 'editor' }; setServerState(state); };
fetchServerState(); }, []);
return ( <> <h1>React Server Components with State Management</h1> <h2>Current Server-Side State:</h2> <p>User: {serverState.user}</p> <p>Role: {serverState.role}</p> <UpdateUserComponent /> <ServerStateComponent /> </> );}
export default App;
useEffect
đảm nhiệm lấy dữ liệu từ server khi component được mount.UpdateUserComponent
và ServerStateComponent
cho phép người dùng cập nhật dữ liệu và hiển thị thông tin phía server tương ứng.Ưu điểm | Nhược điểm |
---|---|
⚡ Giảm tải xử lý cho client | 💻 Hạ tầng server phức tạp hơn |
🧑💻 Cải thiện hiệu năng, mở rộng | 🧩 Cần đồng bộ trạng thái chính xác |
🛠️ Quản lý state nhất quán toàn stack | 🔄 Xử lý bất đồng bộ có thể khó khăn |