Created
November 10, 2024 18:39
-
-
Save yukikim/1e9b35faedacc00ef6cde5e8e83f765f to your computer and use it in GitHub Desktop.
[tsx]sample_useReducer
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
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