Answer the question
In order to leave comments, you need to log in
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())
// index.js
const [state, setState] = useState({});
// actions.js
const someAction = (setState, currentState) => {
setState({
// меняем стейт тут, по сути, так же как в редьюсере
})
}
// callback in someComponent.js
someAction(setState, currentState);
Answer the question
In order to leave comments, you need to log in
something like this?
https://codepen.io/pesockiy/pen/moezJw
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 questionAsk a Question
731 491 924 answers to any question