Skip to content

Instantly share code, notes, and snippets.

@ggorlen
Last active May 31, 2022 05:31
Show Gist options
  • Select an option

  • Save ggorlen/7a6d60a6c17efb7a5e389accd89b2999 to your computer and use it in GitHub Desktop.

Select an option

Save ggorlen/7a6d60a6c17efb7a5e389accd89b2999 to your computer and use it in GitHub Desktop.
preact + hooks + router + unpkg: hooks breaks after navigation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<script type="module">
// reproduction of preact hooks + router failing with unpkg
// see also:
// https://codesandbox.io/s/7z5id?file=/index.html
// https://codesandbox.io/s/htm-preact-hooks-router-jspm-0jhg9
// https://stackoverflow.com/questions/69891883/how-to-use-usestate-hook-with-preact-and-no-build-tools/72442546#
import {Router} from "https://unpkg.com/preact-router@latest?module";
import {h, render, Component} from "https://unpkg.com/preact@latest?module";
import {
useState,
useEffect
} from "https://unpkg.com/preact@latest/hooks/dist/hooks.module.js?module";
import htm from "https://unpkg.com/htm?module";
const html = htm.bind(h);
// class works:
class CounterClass extends Component {
state = {count: 0};
increment = () => {
this.setState(prevState => ({
count: prevState.count + 1
}));
};
render(_, {count}) {
return html`
<button onClick=${this.increment}>
Count: ${count}
</button>
`;
}
}
// hooks fails:
const CounterHooks = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return html`
<button onClick=${increment}>
Count: ${count}
</button>
`;
};
const Nav = () => html`
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
`;
const Home = () => html`
<${CounterHooks} />
<p>Home!</p>
<p>
After navigating to another route, then back to home,
the counter will break if it uses hooks.
</p>
`;
const About = () => html`
<${CounterClass} />
<p>About!</p>
`;
const NotFound = () => html`
<p>404</p>
`;
const App = () => html`
<header>
<${Nav} />
</header>
<main>
<${Router}>
<${Home} path="/" />
<${About} path="/about" />
<${NotFound} default />
<//>
</main>
`;
render(html`<${App} />`, document.body);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment