loading...

re: Build your own web analytics dashboard with Node.js VIEW POST

FULL DISCUSSION
 

Beast of an article! Some great stuff in here.

With this bit at the end -

export const RealTimeItem = () => {
  const [connections, setConnections] = useState(0);
  getConnections((conns) => {
    console.log(conns);
    setConnections(conns);
  });
  return (
    <p>
      {connections}
    </p>
  );
};

If I've read it correctly, I'd suggest wrapping that getConnections call in a useEffect hook (with empty dependencies array) otherwise it will re run every time React goes through a render cycle and resubscribe to the socket event each time.

so -

export const RealTimeItem = () => {
  const [connections, setConnections] = useState(0);

  useEffect(() => {
    getConnections((conns) => {
      console.log(conns);
      setConnections(conns);
    });

    return () => { 
      // unsubscribe from socket here
    };
  }, []);

  return (
    <p>
      {connections}
    </p>
  );
};
code of conduct - report abuse