useUIState is a Vercel AI SDK React hook for reading and updating UI state supplied by an AI context provider. It replaces local conversation state with shared state that descendant components can access. section 4.2.2 section 4.2.3
Use useUIState as part of a provider-based state architecture:
- Create an AI provider with createAI, defining initial UI state such as messages or sidebar visibility. section 4.2.2
- Wrap the application layout with the returned AI component so child components receive the shared context. section 4.2.3
- Call useUIState in a child component to obtain the UI state and update it after user input or an AI response. section 4.2.3
- Keep AI state and UI state distinct: AI state can hold conversation or application data, while UI state drives rendered interface data. section 4.2.2 section 4.5
Chat conversation state
A chat page can replace local conversation state with useUIState, append the user's message, call the continueConversation action, and append the returned assistant response. Input and loading state may remain local, although moving them into UI state is suggested as an exercise. section 4.2.3
Listing 4.9 Including new hooks for managing AI and UI state
export default function Home() {
const [provider, setProvider] = useState('openai');
const [model, setModel] = useState('gpt-4');
const [input, setInput] = useState('');
const [isLoading, setIsloading] = useState(false);
const [conversation, setConversation] =
useUIState(); #1
const [aiState] = useAIState(); #2
const { continueConversation } = useActions(); #3
const handleSubmit = async (e) => {
e.preventDefault();
setUIState((prev) => ({. #4
...prev,
messages: [...prev.messages, { role: 'user', content: input }],
}));
const response =
await continueConversation(input, provider, model); #5
setUIState((prev) => ({
...prev,
messages: [...prev.messages, response],
}));
setInput('');
};
Use the listing to trace how a chat component reads UI state, updates messages, and combines the hook with useAIState and useActions. section 4.2.3
