Search code examples
reactjsreact-hooksaws-chime-sdkamazon-chime

How do I use a custom hook inside of useEffect?


I'm working with Amazon's Chime SDK Component Library for React. The component library has a number of components and hooks available for use.

One of the component is <LocalVideo />. The problem is that it starts with the video disabled. In order to turn it on you use the hook useLocalVideo().

In the examples I've seen they use a button to execute the hook:

const MyComponent = () => {
  const togglevideo = { useLocalVideo };

  return(
    <>
      <LocalVideo />
      <button onClick={toggleVideo}>Toggle</button>
    </>
  );
};

This works fine. But what if I want the LocalVideo component to load enabled? e.g., if I don't want someone to have to click a button?

I've tried several different approaches including:

  1. Add the code directly to the component (this doesn't work, I assume because the hook is called before the render with the LocalVideo component completes).
  2. Adding the code inside useEffect (invalid Hook call errors).

For example:

const MyComponent = () => {
  useEffect( () => {
    useLocalVideo();
   },
  );
const MyComponent = () => {
  const { tileId, isVideoEnabled, setIsVideoEnabled, toggleVideo } = useLocalVideo();

  useEffect( () => {
    setIsVideoEnabled(true);
  }, []
 );

How can I make this hook run after the component renders?


Solution

  • You should call the function toggleVideo inside the useEffect, not the hook useLocalVideo itself:

    const MyComponent = () => {
      const { togglevideo } = useLocalVideo();
    
      useEffect(() => {
        togglevideo();
      }, []);
    
      return (
        <LocalVideo />
      );
    };