Can you compose hooks?
rawrmonstar opened this issue · 1 comments
rawrmonstar commented
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
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>`;
}
});