Skip to content
Docs
Generative UI
useActions

useActions

useActions

useActions is a hook to help you access your Server Actions from the client. It’s required to access these server actions via this hook (because we patched these actions when they’re passing through this context), and if you directly import the actions instead of using useActions, you might run into the current issue of “cannot find client component.” This is particularly useful for building interfaces that require user interactions with the server.

app/action.tsx
import { createAI, createStreamableUI } from 'ai/rsc';
 
async function getStockPrice() {
  // ...
}
 
async function viewStock(symbol: string) {
  "use server"
 
  const uiStream = createStreamableUI(<div>Loading...</div>);
 
  // If you don't wrap this in an IIFE, the stream will block
  // on the await call the Loading state will never be sent
  // to the client.
  (async () => {
    const price = await getStockPrice(symbol);
 
    uiStream.close(
      <div>
        {symbol}: {price}
      </div>
    );
  })();
 
  return {
    id: Date.now(),
    display: uiStream.value,
  };
}
 
export const AI = createAI({
  actions: {
    viewStock,
  },
});
app/components/button.tsx
import { AI } from '../action';
 
export function Button({ setMessages }) {
  const { viewStock } = useActions<typeof AI>();
  const [messages, setMessages] = useUIState<typeof AI>();
 
  return (
    <button
      onClick={async () => {
        const newMessage = await viewStock('NVDA');
 
        setMessages((currentMessages: any) => [...currentMessages, newMessage]);
      }}
    >
      Purchase
    </button>
  );
}

© 2023 Vercel Inc.