<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Bùi Khôi</title>
    <description>The latest articles on Forem by Bùi Khôi (@bi_khi_647aa6dba9175191).</description>
    <link>https://forem.com/bi_khi_647aa6dba9175191</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1529247%2F9ff289ef-e09b-4496-836d-1c26306f126e.png</url>
      <title>Forem: Bùi Khôi</title>
      <link>https://forem.com/bi_khi_647aa6dba9175191</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/bi_khi_647aa6dba9175191"/>
    <language>en</language>
    <item>
      <title>How I solve React's functional component and hooks limitation that cause a lot of troubles/bugs</title>
      <dc:creator>Bùi Khôi</dc:creator>
      <pubDate>Sun, 26 May 2024 04:30:02 +0000</pubDate>
      <link>https://forem.com/bi_khi_647aa6dba9175191/how-i-solve-reacts-functional-component-and-hooks-limitation-that-cause-a-lot-of-troublesbugs-4kj1</link>
      <guid>https://forem.com/bi_khi_647aa6dba9175191/how-i-solve-reacts-functional-component-and-hooks-limitation-that-cause-a-lot-of-troublesbugs-4kj1</guid>
      <description>&lt;h2&gt;
  
  
  I. What's the limitation?
&lt;/h2&gt;

&lt;p&gt;Recently, I took over a project that mostly work on realtime communication(messaging, video call, integrate with different vendors using different sockets). At the moment I joined, there're bunch of bugs that related to glitches stuff.&lt;br&gt;
Take a look at the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Page = () =&amp;gt; {
  const [roomName, setRoomName] = useState();
  const [numberOfParticipant, setNumberOfParticipant] = useState();
  const connection = useVideoCallConnection();

  useEffect(() =&amp;gt; {
    const conference = connection.createConference(roomName);

    conference.on('JOINED', () =&amp;gt; {
      if (numberOfParticipant &amp;gt; 2) {
        conference.setViewMode('grid');
      }
    });

    return () =&amp;gt; {
      conference.off('JOINED');
      conference.disconnect();
    };
  }, [roomName, connection]);

  // Component UI
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It seems fine, but not…&lt;/p&gt;

&lt;p&gt;The main issue is: sometime when &lt;em&gt;createConference&lt;/em&gt; took a few seconds, someone joined the room in the middle of the creation. &lt;em&gt;numberOfParticipants&lt;/em&gt; inside remained the same(&lt;em&gt;numberOfParticipants&lt;/em&gt; is number and wasn't included in the dependencies list). It cause the grid layout turned off, even if the participants number larger than two.&lt;/p&gt;

&lt;p&gt;You might wonder: "why don't we just add &lt;em&gt;numberOfParticipants&lt;/em&gt; to the dep list?"… That's what I thought in the beggining too.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Page = () =&amp;gt; {
  const [roomName, setRoomName] = useState();
  const [numberOfParticipant, setNumberOfParticipant] = useState();
  const connection = useVideoCallConnection();

  useEffect(() =&amp;gt; {
    const conference = connection.createConference(roomName);

    conference.on('JOINED', () =&amp;gt; {
      if (numberOfParticipant &amp;gt; 2) {
        conference.setViewMode('grid');
      }
    });

    return () =&amp;gt; {
      conference.off('JOINED');
      conference.disconnect();
    };
  }, [roomName, connection, numberOfParticipant]);

  // Component UI
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I tried and fixed the problem with grid view but ended up with a new issue: when &lt;em&gt;numberOfParticipant&lt;/em&gt; changed, it's disconnect the current conference and re-create a new one...&lt;/p&gt;

&lt;p&gt;Because the first solution didn't work, I tried another way by seperating the conference init hook into two &lt;em&gt;useEffect&lt;/em&gt; hook:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const Page = () =&amp;gt; {
  const [roomName, setRoomName] = useState();
  const [numberOfParticipant, setNumberOfParticipant] = useState();
  const [conference, setConference] = useState();
  const connection = useVideoCallConnection();

  useEffect(() =&amp;gt; {
    if (conference) {
      conference.on('JOINED', () =&amp;gt; {
        if (numberOfParticipant &amp;gt; 2) {
          conference.setViewMode('grid');
        }
      });
    }

    return () =&amp;gt; {
      if (conference) {
        // Call to this method will throw an error, because conference is already off
        conference.off('JOINED');
      }
    }
  }, [conference, numberOfParticipant]);

  useEffect(() =&amp;gt; {
    const _conference = connection.createConference(roomName) ;

    _conference.connect();
    setConference(_conference);

    _conference.on('LEAVE', () =&amp;gt; {
      setConference (null);
    });

    return () =&amp;gt; {
      _conference.disconnect();
    }

  }, [roomName, connection]);

  // Component UI
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By moving &lt;em&gt;setViewMode&lt;/em&gt; to another &lt;em&gt;useEffect&lt;/em&gt;, we solved the issue(changing the &lt;em&gt;numberOfParticipant&lt;/em&gt; only remove the previous listener instance and add a new one)… So the new code is good, isn't it?&lt;/p&gt;

&lt;p&gt;Unfortunately, it's not. It worked fine when joining conference but not when leaving.&lt;/p&gt;

&lt;p&gt;When the user left the conference(&lt;em&gt;roomName&lt;/em&gt; changed). that one was disconnected and set to null. When it was changed, the &lt;em&gt;conferece.off('joined')&lt;/em&gt; is called and will throw an execption due to the disconnection happened before.&lt;/p&gt;

&lt;p&gt;After a while of trying, I figure it out the limitation here is: &lt;strong&gt;If an outside vavariable value is primnitive, I can't get the latest value of it inside &lt;em&gt;useEffect&lt;/em&gt; without including it in the dependencies list and re-run the cleanup everytime&lt;/strong&gt;(react mentioned the same thing here &lt;a href="https://react.dev/learn/separating-events-from-effects#extracting-non-reactive-logic-out-of-effects"&gt;https://react.dev/learn/separating-events-from-effects#extracting-non-reactive-logic-out-of-effects&lt;/a&gt;)&lt;/p&gt;

&lt;h2&gt;
  
  
  II. Why It happened?
&lt;/h2&gt;

&lt;p&gt;useEffect accepts two params&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A function declaration(&lt;strong&gt;memorized per depdencies list&lt;/strong&gt;)&lt;/li&gt;
&lt;li&gt;An array of dependencies list.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since the function declaration is memorized, the outside variable with priminitive value which is used inside the function will also be memorized per dependencies list. Including a value in the depdencies list make it reactive(changing the variable's value trigger an effect and its cleanup)&lt;/p&gt;

&lt;h2&gt;
  
  
  III. How I solved that?
&lt;/h2&gt;

&lt;p&gt;Because the rootcause is: variable with priminitive value inside &lt;em&gt;useEffect&lt;/em&gt;, we can solve it by duplicate the value with a ref.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Page = () =&amp;gt; {
  const [roomName, setRoomName] = useState();
  const [numberOfParticipant, setNumberOfParticipant] = useState();
  const connection = useVideoCallConnection();
  // Create a ref to use inside effect
  const numberOfParticipantRef = useRef(numberOfParticipant);
  numberOfParticipantRef.current = numberOfParticipant;

  useEffect(() =&amp;gt; {
    const conference = connection.createConference(roomName);

    conference.on('JOINED', () =&amp;gt; {
      // This is reference so it works now!!
      if (numberOfParticipantRef.current &amp;gt; 2) {
        conference.setViewMode('grid');
      }
    });

    return () =&amp;gt; {
      conference.off('JOINED');
      conference.disconnect();
    };
  }, [roomName, connection]);

  // Component UI
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;numberOfParticipantRef&lt;/em&gt; is an object so we could get the latest value inside the effect without re-run anything.&lt;br&gt;
Since my project has a bunch of cases like this and I don't want to do the duplication for all files. I created an npm package hook and a babel plugin to do the job for me&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import useNonReactiveState from 'use-none-reactive-state';

const Page = () =&amp;gt; {
  // Just replace useState with useNonReactiveState and use the babel plugin
  const [roomName, setRoomName] = useNonReactiveState();
  const [numberOfParticipant, setNumberOfParticipant] = useNonReactiveState();
  const connection = useVideoCallConnection();

  useEffect(() =&amp;gt; {
    const conference = connection.createConference(roomName);

    conference.on('JOINED', () =&amp;gt; {
      if (numberOfParticipant &amp;gt; 2) {
        conference.setViewMode('grid');
      }
    });

    return () =&amp;gt; {
      conference.off('JOINED');
      conference.disconnect();
    };
  }, [roomName, connection]);

  // Component UI
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  IV. Conclusion
&lt;/h2&gt;

&lt;p&gt;That's how I solved the problem. Please gimme feedbacks If anything is not correct, I really appreciate that. If you feel interest in the package and the plugin, here's the links:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.npmjs.com/package/use-none-reactive-state"&gt;https://www.npmjs.com/package/use-none-reactive-state&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.npmjs.com/package/babel-plugin-none-reactive-effect"&gt;https://www.npmjs.com/package/babel-plugin-none-reactive-effect&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>react</category>
    </item>
  </channel>
</rss>
