useReducer
React 671 characters
import React, { useReducer } from 'react'
const initialState = { count: 0 }
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 }
case 'decrement':
return { count: state.count - 1 }
default:
throw new Error()
}
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
)
}
Svelte 364 characters (46% less)
<script>
import { writable } from "svelte/store"
const initialValue = 0
const count = writable(initialValue)
count.increment = () => {
count.update((state) => state + 1)
}
count.decrement = () => {
count.update((state) => state - 1)
}
</script>
Count: {$count}
<button on:click={count.decrement}>-</button>
<button on:click={count.increment}>+</button>