import React, {
FC,
Reducer,
useReducer,
} from 'react'
interface State {
hi: string
}
type Action = { type: 'hi', name: string } | { type: 'foo' }
const reducer: Reducer<State, Action> = (state, action) => {
switch (action.type) {
case 'hi':
return { ...state, hi: action.name }
case 'foo':
return { ...state, hi: 'nishi' }
default:
throw new Error('Impl err')
}
}
const initialState: State = {
hi: 'nishi'
}
const App: FC = () => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<button onClick={() => dispatch({type: 'foo'})}>{state.hi}</button>
)
}
More than 5 years have passed since last update.
【コピペ用】 useReducer 最小サンプル
0
Last updated at Posted at 2021-03-10
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme