DEV Community

Using the useReducer Hook in React with TypeScript

Craig Holliday on May 19, 2021

The useReducer hook is an alternative to the useState hook and is preferable when you have complex state logic or when your next state depends on y...
Collapse
 
ratrateroo profile image
ratrateroo

Nice article, helps me to understand useReducer with TypeScript.

lines with:
value: state.count + payload
value: state.count - payload

should be changed to:
count: state.count + payload
count: state.count - payload

and a few edit in + and - buttons.

Collapse
 
lexlohr profile image
Alex Lohr

I believe useReducer is meant for cases where the transitions between the states (actions) are required to understand the underlying logic. In any other case, better use useState.

Collapse
 
swizzard profile image
sam

there's nothing useReducer can do that useState can't, and vice versa. the choice is just about clarity.

Collapse
 
lexlohr profile image
Alex Lohr

Exactly. And the choice should depend on whether the transitions are more meaningful to explain the task than the state itself.

Collapse
 
menard_codes profile image
Menard Maranan • Edited

On your second use case, useReducer using the Partial type for state updates, I think good 'ol useState is just enough.

interface LoadingState {
    loaded: boolean;
    loading: boolean;
    error: Error | null;
}

function LoadingComponent() {
    const [state, setState] = useState<LoadingState>({
        loaded: false,
        loading: true,
        error: null
    })

    useEffect(() => {
        ...
        setState(prev => ({
            ...prev,
            loaded: true,
            loading: true
        }))
        ...
    }, [])

    return (
        <div>
            ...
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
seojeek profile image
Alex Vallejo

This is an over simplistic example. What if the payload can span multiple types but depend on the action being called?

Collapse
 
maxquesar profile image
Kris • Edited

There is a typo in your first example
value: state.count + payload,

Should be :
count: state.count + payload,

Collapse
 
flyingace profile image
David Cameron

I appreciated this article, so tyvm! I do think you should implement the changes that @ratrateroo has called out though or at least reply with an explanation of why they're not valid.

Collapse
 
herberthk profile image
herberthk

Thank you

Collapse
 
prashi_cn profile image
Solitary

Between useReducer and useState , which is better for nested objects or arrays?

Collapse
 
marlonx19 profile image
Marlon Englemam

UseReducer is better for that case