Last active
September 3, 2021 01:14
-
-
Save peerreynders/8c18513dd8ee12ec0a374a39ba2c03b5 to your computer and use it in GitHub Desktop.
"use initializer" custom hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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