Reputation: 175
I use react hooks useReducer
that contains my state, let's say I have 3 state fields - a
,b
and c
.
Those fields tie together and mostly change together - so the reducer function is cohesive.
If I have different state field d
that is not cohesive to the other state - should I use both useState
(for d
) and useReducer
(for a
,b
and c
) at the same component or it's better to use the same reducer function? Moreover - if I have more fields like d
that changes in similar places - should I use 2 seperate reducers?
What is the best practice for this case?
Upvotes: 8
Views: 2679
Reputation: 549
I tend to try and abstract the useReducer
to a global context and use useContext
in conjunction with the reducer to get my application state. However, sometimes it makes sense to use useContext
and useState
if the component has an internal state. That being said, I don't think there are any hard and fast rules for hooks at the moment, so I would read up more and make the best choices for your team. That being said, I do agree with what IliasT said about cramming state into one useState. If you go with the useState
hook use one for each piece of state and don't try and make an object that controls the state.
Upvotes: 2
Reputation: 4301
My advice would be use both useState
and useReducer
, given useReducer
is just an abstraction around useState
.
Just like you wouldn't try to cram all the state of the component into one useState
hook, you likely should also avoid doing that for useReducer
.
Upvotes: 6