DEV Community

Discussion on: React with Typescript

 
joaolss profile image
João Lucas Silva • Edited

Because you avoid shooting youself on the foot and wrongly mutating the state object, you can use immer to immutability, and you can deal with more complex trabsformation in the reducer, and in last case you can write I reducer simple enough that it just contains the code that you would have to write inside setState to mutate a variable inside the object, so you dont have to write it in each setState (or useCallback just to do that) instead you can do this logic in the reducer and use the dispatch as the setState, so yes it is definitely better to use the useReducer hook and there is no benefit at all in using useState for objects

Edit: putting a example so you can see what im talking about:

const reducer = (state, action) => ({ ...state, ...action })
...
const [state,setState] = useReducer(reducer, { a: 1, b: 2})
...
setState({ a: 3 })
// new state: { a: 3, b: 2 }
Enter fullscreen mode Exit fullscreen mode

same amount of code, safer/cleaner code

Thread Thread
 
konstagap profile image
konstagap • Edited

"Because you avoid shooting yourself on the foot and wrongly mutating the state object" - how is your example prevents that? u not dispatching anything, u basically using useReducer as a useState. Anyways, it's good if it works for you, I don't know how come it is safer/cleaner than this
const [state,setState] = useState({ a: 1, b: 2});
setState(prev =>({...prev, a:3 });
Notice how it does the same thing without writing a reducer?
BTW you using the reducer wrong. To use useReducer right, to "avoid shooting yourself on the foot" refer to docs reactjs.org/docs/hooks-reference.h... .
I know you have seen them, but maybe take a second look so you can see what I'm talking about.

Thread Thread
 
joaolss profile image
João Lucas Silva

it is safer because you dont need to remember to spread the old object everytime you need to update the state, it is cleaner because you are only spreading an object on the reducer, and you don’t have to rely on other devs doing it. “You not dispatching anything” you clearly don’t know the difference between reducer and flux paradigm, they are connected but are not the same, the documentation states: “ useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values” in verbatim, tell me where in there it shows that im wrong