Skip to content

Instantly share code, notes, and snippets.

@himanshupal
Created June 10, 2023 17:47
Show Gist options
  • Save himanshupal/9f8673f385291fe256bb635406cc96ed to your computer and use it in GitHub Desktop.
Save himanshupal/9f8673f385291fe256bb635406cc96ed to your computer and use it in GitHub Desktop.
Typed example of React useReducer hook
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