H
H
HuckleberryDev2019-12-20 18:54:20
css
HuckleberryDev, 2019-12-20 18:54:20

Why do we need useReducer (if there is useState)?

Preamble: I've been using React Redux Typescript for a long time. I recently started getting into hooks. I'm trying to build an application with a global state passed through the context.
Actually the question is: why do you need useReducer with all its boilerplate, if you can do the same with useState, just wrap all state modifications in the same action functions?
Those. instead of:

// index.js
const reducer (state, action) => {
    switch (action.type) {
        case 'actionType': {
            return {
                // меняем стейт тут
            }
        }
    }
}
const [state, dispatch] = useReducer(reducer, {})

// actions.js
const someAction = () => {
    return {
        type: 'actionType'
    }
}

// callback in someComponent.js
dispatch(someAction())

use:
// index.js
const [state, setState] = useState({});

// actions.js
const someAction = (setState, currentState) => {
    setState({
        // меняем стейт тут, по сути, так же как в редьюсере
    })
}

// callback in someComponent.js
someAction(setState, currentState);

I do not see any benefit in the first approach, except for the formalities that bloat the code. Or am I still missing something?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mikhail Vlasov, 2019-02-12
@Hello00

Without fieldset:

N
not Doctor Strange, 2019-02-28
@StrangeNotADoctor

something like this?
https://codepen.io/pesockiy/pen/moezJw

A
abberati, 2019-12-20
@HuckleberryDev

useReducer is needed in order to encapsulate the methods of changing the state in one place - inside the reducer. The approach described by you loses in "comprehensibility" - you smear storage logic inside actionCreator'ov.
And here is an interesting note about the store on hooks
https://gist.github.com/XaveScor/99431c573b53b8a0c...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question