Skip to content

Instantly share code, notes, and snippets.

@yukikim
Created November 10, 2024 18:39
Show Gist options
  • Save yukikim/1e9b35faedacc00ef6cde5e8e83f765f to your computer and use it in GitHub Desktop.
Save yukikim/1e9b35faedacc00ef6cde5e8e83f765f to your computer and use it in GitHub Desktop.
[tsx]sample_useReducer
import { useReducer } from 'react'
// reducerが受け取るactionの型を定義します
type Action = 'DECREMENT' | 'INCREMENT' | 'DOUBLE' | 'RESET'
// 現在の状態とactionにもとづいて次の状態を返します
const reducer = (currentCount: number, action: Action) => {
switch (action) {
case 'INCREMENT':
return currentCount + 1
case 'DECREMENT':
return currentCount - 1
case 'DOUBLE':
return currentCount * 2
case 'RESET':
return 0
default:
return currentCount
}
}
type CounterProps = {
initialValue: number
}
const Counter = (props: CounterProps) => {
const { initialValue } = props
const [count, dispatch] = useReducer(reducer, initialValue)
return (
<div>
<p>Count: {count}</p>
{/* dispatch関数にactionを渡して、状態を更新します */}
<button onClick={() => dispatch('DECREMENT')}>-</button>
<button onClick={() => dispatch('INCREMENT')}>+</button>
<button onClick={() => dispatch('DOUBLE')}>×2</button>
<button onClick={() => dispatch('RESET')}>Reset</button>
</div>
)
}
export default Counter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment