jlengstorf / honkify-demo

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React example does not use best practices

lambert-velir opened this issue · comments

There is a potential bug with the React example. If the Honker is unmounted from the page, honkify is not unregistered. To solve this, the example should utilize the useEffect hook:

import React, { useEffect, useState } from "react";
import honkify from "honkify";

const Honker = () => {
  const [isActive, setActive] = useState(false);

  useEffect(() => {
    if (isActive) {
      const unregister = honkify();
      return () => unregister();
    }
  }, [isActive]);

  const toggleHonk = () => {
    setActive(isActive => !isActive);
  };

  return (
    <button onClick={toggleHonk} className="no-honk">
      {isActive ? "unhonk" : "honkify!"}
    </button>
  );
};

export default Honker;

In the useEffect, unregister will be called if the isActive state is false or if the Honker is unmounted.