wtnbass / fuco

Functional Component like React, but for Web Components.
MIT License
74 stars 2 forks source link

Can you compose hooks? #45

Closed rawrmonstar closed 4 years ago

rawrmonstar commented 4 years ago

One of the most powerful features of hooks in React is the ability to create your own composed of other hooks (see https://usehooks.com/ for examples of what I mean). Is this possible in this library? It would be nice to provide a documented example. IMO creating your own hooks is one of the annoying things with a similar library such as https://github.com/matthewp/haunted

wtnbass commented 4 years ago

Hi @rawrmonstar. Thank you for the question! It is also possible in fuco.

Here is a simple example for hash router:

// 1. Define compose hooks.
function useHashRouter() {
  const [hash, setHash] = useState(location.hash.slice(1));
  useEffect(() => {
    const hashChanged = () => setHash(location.hash.slice(1));
    window.addEventListener("hashchange", hashChanged);
    hashChanged();
    return () => {
      window.removeEventListener("hashchange", hashChanged);
    };
  }, []);
  return hash;
}

// 2. Use it in fuco component.
defineElement("app-shell", () => {
  const hash = useHashRouter();
  switch (hash) {
    case "/":
      return html`<app-home></app-home>`;
    case "/about":
      return html`<app-about></app-about>`;
    default:
      return html`<not-found></not-found>`;
  }
});