Skip to content

Instantly share code, notes, and snippets.

@peerreynders
Last active September 3, 2021 01:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save peerreynders/8c18513dd8ee12ec0a374a39ba2c03b5 to your computer and use it in GitHub Desktop.
Save peerreynders/8c18513dd8ee12ec0a374a39ba2c03b5 to your computer and use it in GitHub Desktop.
"use initializer" custom hook
<!doctype html>
<html lang="eng">
<head>
<meta charset="utf-8"/>
<title>useInitializer</title>
</head>
<body>
<script type="module">
import { html, render, useState } from '//unpkg.com/htm/preact/standalone.mjs';
// custom hook "use initializer"
function useInit(init, ...args) {
const tuple = useState(null);
const [state, setState] = tuple;
if(state !== null) {
return tuple;
}
const initState = init(setState, ...args);
setState(initState);
return [initState, setState];
}
// Component Parts
function initCounter(setState, startAt) {
const increment = state => ({...state, count: state.count + 1});
const clickHandler = () => setState(increment);
return {
count: Number(startAt),
clickHandler
};
}
// Component
function Counter({startAt}) {
const [{count, clickHandler}, setState] = useInit(initCounter, startAt);
return html`
<p>
<button onClick=${clickHandler}>Click me</button>
</p>
<output>You clicked ${count} times</output>
`;
}
function App() {
return html`<${Counter} startAt="12" />`;
}
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