Building a Multi-Turn Chatbot with the Claude API in React
When building RECORD.AI, I needed to manage multi-turn
conversation state with the Anthropic Claude API. Here's
how I structured it.
The Message Payload
Claude expects messages in this format:
[
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi! How can I help?" },
{ role: "user", content: "What is function calling?" }
]
Managing State in React
const [messages, setMessages] = useState([])
const sendMessage = async (userInput) => {
const newMessages = [...messages, { role: "user", content: userInput }]
setMessages(newMessages)
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "claude-sonnet-4-20250514",
max_tokens: 1000,
messages: newMessages
})
})
const data = await response.json()
const assistantReply = data.content[0].text
setMessages([...newMessages, { role: "assistant", content: assistantReply }])
}
Key Takeaway
Always send the full conversation history on every request —
Claude has no memory between calls.
Top comments (0)