Skip to main content

Generated Hooks

BAML automatically generates a type-safe React hook for each BAML function. Each hook follows the naming pattern use{FunctionName} and supports both streaming and non-streaming modes.

Basic Usage​

import { useWriteMeAStory } from "@/baml_client/react/hooks";

// Basic usage with streaming enabled by default
const hook = useWriteMeAStory();

// Access streaming and final data
const { data, streamData, finalData } = hook;

// Track request state
const { isLoading, isStreaming, isPending, isSuccess, isError } = hook;

// Execute the function
await hook.mutate("A story about a brave AI");

// Reset state if needed
hook.reset();

BAML Function:

class Story {
title string @stream.not_null
content string @stream.not_null
}

function WriteMeAStory(input: string) -> Story {
client openai/gpt-4
prompt #"
Tell me a story.

{{ ctx.output_format() }}

{{ _.role("user") }}

Topic: {{input}}
"#
}

HookInput​

The hook accepts an optional configuration object. See Hook Input for details.

PropertyTypeDescription
streambooleanEnable streaming mode. Defaults to true
onStreamData(response?) => voidCallback for streaming updates
onFinalData(response?) => voidCallback when request completes
onData(response?) => voidUnified callback for both streaming and final
onError(error: BamlErrors) => voidCallback when error occurs

HookOutput​

The hook returns an object with the following properties. See Hook Output for details.

PropertyTypeDescription
dataFinalData | StreamData | undefinedCurrent response data
finalDataFinalData | undefinedFinal response (when complete)
streamDataStreamData | undefinedLatest streaming update
errorBamlErrors | undefinedError information if failed
isLoadingbooleanRequest in progress
isPendingbooleanRequest pending (not yet streaming)
isStreamingbooleanCurrently streaming
isSuccessbooleanCompleted successfully
isErrorbooleanRequest failed
statusHookStatusCurrent state: 'idle' | 'pending' | 'streaming' | 'success' | 'error'
mutate(...args) => PromiseExecute the BAML function
reset() => voidReset hook state

Examples​

With Callbacks​

function StoryComponent() {
const hook = useWriteMeAStory({
stream: true,
onStreamData: (text) => console.log("Streaming:", text),
onFinalData: (text) => console.log("Complete:", text),
onError: (error) => console.error("Error:", error)
});

return (
<div>
<button onClick={() => hook.mutate("A dragon story")} disabled={hook.isLoading}>
Generate Story
</button>
{hook.isStreaming && <span>Generating...</span>}
{hook.data && <p>{hook.data.content}</p>}
</div>
);
}

Non-Streaming Mode​

function NonStreamingComponent() {
const hook = useWriteMeAStory({ stream: false });

return (
<div>
<button onClick={() => hook.mutate("A sci-fi story")} disabled={hook.isLoading}>
Generate
</button>
{hook.isPending && <span>Loading...</span>}
{hook.finalData && <p>{hook.finalData.content}</p>}
</div>
);
}

Error Handling​

function WithErrorHandling() {
const hook = useWriteMeAStory({
onError: (error) => {
if (error instanceof BamlValidationError) {
console.error("Validation failed:", error.raw_output);
}
}
});

return (
<div>
{hook.isError && <div className="error">{hook.error?.message}</div>}
<button onClick={() => hook.mutate("Story topic")}>Generate</button>
</div>
);
}

See Also​