useSession
The useSession
hook allows you to get the Talk.Session
TalkJS object in any child component of
the <Session>
component:
1import { useEffect } from 'react';2import { useSession } from '@talkjs/react';34function MyComponent(props) {5 const session = useSession(); // Talk.Session | undefined67 useEffect(() => {8 if (session?.isAlive) {9 session.getOrCreateConversation('welcome').sendMessage('hi');10 }11 }, [session]);12}
Make sure you always check the isAlive
property to ensure that the object is not destroyed, because React is prone to trigger race conditions here (especially when React.StrictMode
is enabled or when using a development setup with Hot Module Reloading, both of which cause a lot of destroying).