Created
June 10, 2023 17:47
-
-
Save himanshupal/9f8673f385291fe256bb635406cc96ed to your computer and use it in GitHub Desktop.
Typed example of React useReducer hook
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
import type { Reducer } from 'react' | |
import { Fragment, useReducer } from 'react' | |
interface IReducerState { | |
name: string | |
age: number | |
} | |
type IReducerAction = | |
| { | |
type: 'changed_age' | |
} | |
| { | |
type: 'changed_name' | |
newName: string | |
} | |
const initialState: IReducerState = { name: 'Taylor', age: 42 } | |
function Form() { | |
const [state, dispatch] = useReducer<Reducer<IReducerState, IReducerAction>>((state, action) => { | |
switch (action.type) { | |
case 'changed_age': { | |
return { | |
...state, | |
age: state.age + 1, | |
} | |
} | |
case 'changed_name': { | |
return { | |
...state, | |
name: action.newName, | |
} | |
} | |
} | |
}, initialState) | |
function handleButtonClick() { | |
dispatch({ type: 'changed_age' }) | |
} | |
const handleInputChange: React.ChangeEventHandler<HTMLInputElement> = (e) => { | |
dispatch({ | |
type: 'changed_name', | |
newName: e.target.value, | |
}) | |
} | |
return ( | |
<Fragment> | |
<input value={state.name} onChange={handleInputChange} /> | |
<button onClick={handleButtonClick}>Increment age</button> | |
<p> | |
Hello, {state.name}. You are {state.age}. | |
</p> | |
</Fragment> | |
) | |
} | |
export default Form |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment