Skip to main content

Hooks

This page documents all the available custom hooks provided by the library. These hooks allow you to interact (externally from your own components) with various parts of the chatbot, such as toggling audio, handling messages, and controlling the chat window state!

Tip

Hooks are only relevant if you intend to interact with the chatbot functionalities (e.g. toggle audio or chat window) from outside the chatbot and within your own component. If you have no such use case, you may skip hooks entirely!

Note that in order to import and use these custom hooks within your components, you first need to import ChatBotProvider and nest your components as its children. We'll look at 2 scenarios below.

Scenario 1: If you have no need for custom hooks, then you do not need to import ChatBotProvider and can simply use ChatBot. This is likely the scenario for a vast majority of users:

import ChatBot from "react-chatbotify";

const MyComponent = () => {
return (
<ChatBot/> {/* no custom hooks needed */}
);
};

Scenario 2: If you require custom hooks to interact with the chatbot (e.g. toggle audio) from within your own components, you need to import ChatBotProvider and ensure that your components that need the hooks are nested within it:

import ChatBot, { ChatBotProvider } from "react-chatbotify";

const MyComponent = () => {
return (
<>
<MyNotNestedComponent> {/* unable to access custom hooks */}
<ChatBotProvider>
<MyNestedComponent> {/* able to access custom hooks (e.g. useAudio) */}
<ChatBot/>
</ChatBotProvider>
</>
);
};
import { useAudio } from "react-chatbotify";

const MyNestedComponent = () => {
// can use custom hook
const { toggleAudio } = useAudio();

return (
<button onClick={toggleAudio}></button>
)
};

const MyNotNestedComponent = () => {
// error, cannot use custom hook since outside of ChatBotProvider
const { toggleAudio } = useAudio();

return (
<button onClick={toggleAudio}></button>
)
};
Warning

It is a common mistake to import these custom hooks from a component outside of <ChatBotProvider>. If you're running into issues, make sure to check that your component is nested properly as a child of <ChatBotProvider>!

Tip

An extensive example featuring how various hooks may be used can be found here.

Overview

Below is a list of available hooks along with a brief description for each of them:

NameDescription
useAudioManages audio functionalities, such as toggling audio on or off.
useBotIdAllows retrieving of bot id (mainly for plugin developers).
useChatHistoryHandles loading, retrieving and setting of chat history messages.
useChatWindowManages the state of the chatbot window (open/close).
useFirstInteractionDetects and tracks the user's first interaction with the chatbot.
useFlowAllows retrieving and restarting chatbot flow and tracks if flow has started.
useMessagesHandles sending, clearing, and retrieving messages in the chatbot.
useNotificationsManages chatbot notifications, such as toggling notifications on or off.
useOnRcbEventRegisters a chatbot event with corresponding handler.
usePathsManages chatbot conversation paths, such as navigation.
useSettingsAccesses and modifies chatbot settings.
useStylesAccesses and modifies chatbot styles.
useTextAreaManages the text input area of the chatbot, including setting and clearing values.
useToastsManages toasts shown within the chatbot, such as showing or missing them.
useVoiceManages voice functionality, such as toggling voice on or off.

Hook Details

Below is a detailed description of each hook and the functions they expose.


useAudio

Description

The useAudio hook allows you to track and manage the chatbot's audio functionality.

Return Values

NameTypeParameterDescription
audioToggledOnboolean-Indicates if the chatbot audio is currently on or off.
toggleAudioasync functionactive (optional) - boolean indicating desired end stateToggles the chatbot audio on or off.
speakAudioasync functiontext (required) - string representing text to speak outSpeaks out the given text using the chatbot audio settings.

Code Example

import { useAudio } from "react-chatbotify";

const MyNestedComponent = () => {
const { toggleAudio } = useAudio();

return (
<button onClick={toggleAudio}></button>
)
};

useBotId

Description

The useBotId hook allows you to retrieve the bot id (mainly for plugin developers).

Return Values

NameTypeParameterDescription
getBotIdfunction -Retrieves the bot id.

Code Example

import { useBotId } from "react-chatbotify";

const MyNestedComponent = () => {
const { getBotId } = useBotId();

return (
<button onClick={getBotId}></button>
)
};

useChatHistory

Description

The useChatHistory hook allows you to show, retrieve and set chat history messages.

Return Values

NameTypeParameterDescription
showChatHistoryfunction-Shows the chat history messages on the chatbot.
getHistoryMessagesfunction-Retrieves the chat history messages.
setHistoryMessagesfunctionmessages (required) - Message[] to set history withSets the chat history messages (note that this is permanent).
hasChatHistoryLoadedboolean-Boolean indicating if chat history has been loaded.

Code Example

import { useChatHistory } from "react-chatbotify";

const MyNestedComponent = () => {
const { showChatHistory } = useChatHistory();

return (
<button onClick={showChatHistory}></button>
)
};

useChatWindow

Description

The useChatWindow hook allows you to track and manage the chatbot's window state.

Return Values

NameTypeParameterDescription
isChatWindowOpenboolean-Indicates if the chat window is currently open or close.
toggleChatWindowasync functionactive (optional) - boolean indicating desired end stateToggles the chat window open or close.
toggleIsBotTypingasync functionactive (optional) - boolean indicating desired end stateToggles the bot typing indicator.
scrollToBottomfunctionduration (optional): number representing duration in milliseconds to scroll, defaults to 0Scrolls to the bottom of the chat window.

Code Example

import { useChatWindow } from "react-chatbotify";

const MyNestedComponent = () => {
const { toggleChatWindow } = useChatWindow();

return (
<button onClick={toggleChatWindow}></button>
)
};

useFirstInteraction

Description

The useFirstInteraction hook allows you to track if a page has been interacted with.

Return Values

NameTypeParameterDescription
hasInteractedPageboolean-Indicates if the page has been interacted with.

Code Example

import { useEffect } from "react";
import { useFirstInteraction } from "react-chatbotify";

const MyNestedComponent = () => {
const { hasInteractedPage } = useFirstInteraction();

useEffect(() => {
// do something if has interacted
}, [hasInteractedPage])

return (
<ExampleComponent/>
)
};

useFlow

Description

The useFlow hook allows you to get a flow, restart a flow and track if a flow has started.

Return Values

NameTypeParameterDescription
hasFlowStartedboolean-Indicates if the chatbot flow has started.
getFlowfunction-Retrieves the chatbot flow.
restartFlowasync function-Restarts the chatbot flow.

Code Example

import { useEffect } from "react";
import { useFirstInteraction } from "react-chatbotify";

const MyNestedComponent = () => {
const { hasFlowStarted } = useFirstInteraction();

useEffect(() => {
// do something if flow has started
}, [hasFlowStarted])

return (
<ExampleComponent/>
)
};

useMessages

Description

The useMessages hook allows you to track and manage the chatbot's messages.

Return Values

NameTypeParameterDescription
injectMessageasync functionRefer hereA utility function used to inject a message into the chat, identical to params.injectMessage.
simulateStreamMessageasync functionRefer hereA utility function used to simulate streaming of messages into the chat, identical to params.simulateStreamMessage.
streamMessageasync functionRefer hereA utility function used to stream messages into the chat, identical to params.streamMessage.
endStreamMessageasync functionRefer hereA utility function used to indicate the end of an existing message stream, identical to params.endMessageStream.
removeMessageasync functionRefer hereA utility function used to remove a message from the chat, identical to params.removeMessage.
messagesArray<Message>-Array containing all messages currently shown in the chatbot.
replaceMessagesfunctionnewMessages (required) - Message[] to replace chat withDirectly replaces the current messages with provided messages.

Code Example

import { useEffect } from "react";
import { useMessages } from "react-chatbotify";

const MyNestedComponent = () => {
const { injectMessage } = useMessages();

useEffect(() => {
// inject custom message
injectMessage("my custom message");
}, [])

return (
<ExampleComponent/>
)
};

useNotifications

Description

The useNotifications hook allows you to track and manage the chatbot's notifications functionality.

Return Values

NameTypeParameterDescription
notificationsToggledOnboolean-Indicates if the chatbot notifications is currently on or off.
toggleNotificationsasync functionactive (optional) - boolean indicating desired end stateToggles the chatbot notifications on or off.
playNotificationSoundfunction-Plays the notification sound.

Code Example

import { useNotifications } from "react-chatbotify";

const MyNestedComponent = () => {
const { toggleNotifications } = useNotifications();

return (
<button onClick={toggleNotifications}></button>
)
};

useOnRcbEvent

Description

The useOnRcbEvent hook allows you to register a chatbot event with its corresponding handler. It accepts 2 parameters, the first being a RcbEvent (provided as an enum export by the library) and the second being the corresponding event handler. Note that the hook does not return any value since it simply registers an event. This is commonly used in plugins which rely on listening on events and taking actions via hooks.

Code Example

import { useEffect } from "react";
import { useOnRcbEvent, RcbEvent, RcbChangePathEvent } from "react-chatbotify";

const MyNestedComponent = () => {
const handler = (event: RcbChangePathEvent) => {
// handle change path logic
}

// listens on the change path event
useOnRcbEvent(RcbEvent.CHANGE_PATH, handler);

return (
<ExampleComponent/>
)
};

usePaths

Description

The usePaths hook allows you to track and manage the chatbot's paths.

Return Values

NameTypeParameterDescription
getCurrPathfunction-Retrieves the current path of the user.
getPrevPathfunction-Retrieves the previous path of the user.
goToPathfunctionRefer hereSends the user to a specified path, identical to params.goToPath.
pathsArray<string>-Array containing all paths the user has taken in order.
replacePathsfunctionnewPaths (required) - string[] containing paths to replace withDirectly replaces the current paths with provided paths (hardly a reason to do this, think twice).

Code Example

import { useEffect } from "react";
import { usePaths } from "react-chatbotify";

const MyNestedComponent = () => {
const { goToPath } = usePaths();

useEffect(() => {
// go to custom path
goToPath("my-custom-path");
}, [])

return (
<ExampleComponent/>
)
};

useSettings

Description

The useSettings hook allows you to track and manage the chatbot's settings.

Return Values

NameTypeParameterDescription
settingsSettings-Represents the current settings of the chatbot.
replaceSettingsfunctionnewSettings (required) - Settings to replace withDirectly replaces the current settings with provided settings.
updateSettingsfunctionfields (required) - Settings fields to updateModifies and merges the provided settings with existing settings.

Code Example

import { useEffect } from "react";
import { useSettings } from "react-chatbotify";

const MyNestedComponent = () => {
const { settings, updateSettings } = useSettings();

useEffect(() => {
if (settings.general?.embedded) {
// disable audio if chatbot is embedded
updateSettings({audio: {disabled: false}})
}
}, [])

return (
<ExampleComponent/>
)
};

useStyles

Description

The useStyles hook allows you to track and manage the chatbot's styles.

Return Values

NameTypeParameterDescription
stylesStyles-Represents the current styles of the chatbot.
replaceStylesfunctionnewStyles (required) - Styles to replace withDirectly replaces the current styles with provided styles.
updateStylesfunctionfields (required) - Styles fields to updateModifies and merges the provided styles with existing styles.

Code Example

import { useEffect } from "react";
import { useStyles } from "react-chatbotify";

const MyNestedComponent = () => {
const { updateStyles } = useStyles();

useEffect(() => {
// update header style
updateStyles({headerStyle: {background: "red"}})
}, [])

return (
<ExampleComponent/>
)
};

useTextArea

Description

The useTextArea hook allows you to track and manage the chatbot's text area field.

Return Values

NameTypeParameterDescription
textAreaDisabledboolean-Indicates if the text area is disabled.
toggleTextAreaDisabledfunctionactive (optional) - boolean indicating desired end stateToggles the text area disabled state.
textAreaSensitiveModeboolean-Indicates if the text area is in sensitive mode.
toggleTextAreaSensitiveModefunctionactive (optional) - boolean indicating desired end stateToggles the text area sensitive mode.
getTextAreaValuefunction-Retrieves the string value inside the text area.
setTextAreaValueasync functionRefer hereSets the value inside the text area, identical to params.setTextAreaValue.
focusTextAreafunction-Focuses on the text area.
blurTextAreafunction-Blurs (lose focus of) the text area.

Code Example

import { useEffect } from "react";
import { useTextArea } from "react-chatbotify";

const MyNestedComponent = () => {
const { focusTextArea } = useTextArea();

useEffect(() => {
// focus on chatbot input text area
focusTextArea()
}, [])

return (
<ExampleComponent/>
)
};

useToasts

Description

The useToasts hook allows you to track and manage the chatbot's toasts.

Return Values

NameTypeParameterDescription
showToastasync functionRefer hereShows a toast in chat, identical to params.showToast.
dismissToastasync functionRefer hereDismisses a toast from chat, identical to params.dismissToast.
toastsArray<Toast>-Array containing all toasts currently shown in the chatbot.
replaceToastsfunctionnewToasts (required) - Toast[] to replace withDirectly replaces the current toasts with provided toasts.

Code Example

import { useEffect } from "react";
import { useToasts } from "react-chatbotify";

const MyNestedComponent = () => {
const { showToast } = useToasts();

useEffect(() => {
// shows a toast for 3 seconds
showToast("Hello, I'm a toast message!", 3000)
}, [])

return (
<ExampleComponent/>
)
};

useVoice

Description

The useVoice hook allows you to track and manage the chatbot's voice functionality.

Return Values

NameTypeParameterDescription
voiceToggledOnboolean-Indicates if the chatbot voice is currently on or off.
toggleVoiceasync functionactive (optional) - boolean indicating desired end stateToggles the chatbot voice on or off.

Code Example

import { useVoice } from "react-chatbotify";

const MyNestedComponent = () => {
const { toggleVoice } = useVoice();

return (
<button onClick={toggleVoice}></button>
)
};