State is mutable information that changes as an application runs. In React, component state supports interactive UI. An AI chat application also needs conversation history and model context, which may be used on the server rather than displayed in the browser. section 2.4 section 4.2
Keep two related kinds of state distinct:
- AI state holds serializable data used by the model and server, such as conversation messages, timestamps, conversation IDs, and JSON representations of generated components. It can be stored for later use. section 4.2.1
- UI state holds client-side elements and interaction values, such as rendered components, loading indicators, and open menus. It renders the current experience but cannot be transferred directly to the server. section 4.2.1
A prompt starts in a client component. A server action uses AI state to call the model; generated content then updates the AI context and the visible UI. Keeping those responsibilities separate improves server–client synchronization without sending every piece of model context to the browser. section 4.2.1 section 4.2
Listing 4.6 Example creating an AI provider
const AI = createAI({
actions: { #1
fetchUserData: async (userId) => {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
return data;
},
updateUserSettings: async (settings) => {
await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(settings),
});
}
},
initialAIState: {
userProfile: { name: '', email: '' },
settings: { theme: 'light', notifications: true },
}, #2
initialUIState: {
isSidebarOpen: false,
}, #3
});
...
const AppLayout = ({ children }) => {
return (
<AI>. #4
{children}
</AI>
)
}
The provider setup defines initial AI and UI states alongside available actions, then wraps the application layout so components can access them. section 4.2.2
Conversation updates
In a streaming chat, initialize AI state with an empty history and UI state with an empty messages list. A server action reads history through getMutableAIState and calls streamUI; the client uses useActions to submit a prompt and useUIState to add the user's message and the returned display component. Local useState can still hold input and loading values. section 4.2.3
For durable conversations, save AI state after an update completes and load saved state as the provider's initial AI state. This applies to serializable AI data, not rendered UI elements. section 4.2.2 section 4.2.1






































