Created
December 4, 2019 19:38
-
-
Save kristoferjoseph/ff14acdecb987e460a6a6bbee27023c5 to your computer and use it in GitHub Desktop.
Preact hooks example: useReducer, useEffect. No compile step.
This file contains hidden or 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="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<section id="root"></section> | |
<script type="module" crossorigin> | |
import { h, render } from 'https://unpkg.com/preact@latest?module' | |
import { useReducer, useEffect } from 'https://unpkg.com/preact@latest/hooks/dist/hooks.module.js?module' | |
import htm from "https://unpkg.com/htm@latest/dist/htm.module.js?module" | |
const html = htm.bind(h) | |
const initialState = 0 | |
const reducer = (state, action) => { | |
switch (action) { | |
case 'increment': return state + 1 | |
case 'decrement': return state - 1 | |
case 'reset': return 0 | |
default: throw new Error('Unknown Action') | |
} | |
} | |
const Counter = () => { | |
const [count, dispatch] = useReducer(reducer, initialState) | |
useEffect(() => { | |
document.title = `Count is ${count}` | |
}) | |
const increment = () => dispatch('increment') | |
const decrement = () => dispatch('decrement') | |
const reset = () => dispatch('reset') | |
return html` | |
<div> | |
<p>Count: ${count}</p> | |
<button onclick=${increment}>+</button> | |
<button onclick=${decrement}>-</button> | |
<button onclick=${reset}>reset</button> | |
</div> | |
` | |
} | |
render(html`<${Counter}/>`, document.getElementById('root')) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment