DEV Community

Discussion on: Feature request: [state,,updateState] = useState(...)

Collapse
 
wozzo profile image
Warren

Since hooks I've been splitting these up in to separate useState calls (one for each property). Is there an advantage of keeping it in a single object?

Collapse
 
ipavlenko profile image
Igor Pavlenko

You are right, better example is required here.
P.S. Example updated, thanks

Collapse
 
wozzo profile image
Warren • Edited

I see. You could achieve this with a custom hook.
Something like (am on phone so forgive mistakes please) :

function useObjectState(object initial) {
    const [ value, setValue] = useState(initial) 
    const updateState = (object newState) => setState({...value, ...newState}) 
    return [ value, updateState] 
} 
Thread Thread
 
ipavlenko profile image
Igor Pavlenko • Edited

Yes, I can, thanks!
Just wonder why this is not implemented in react.

But you have a little issue in your example.
You use current state, not the last state in you fragment.
Be careful with sequential updates or use callback in setState call to reference prevState

Thread Thread
 
wozzo profile image
Warren

Missed the useState call. Fixed now. I imagine it's not been implemented because they're going for a more minimalist approach. I.e. By giving us the simplest of hooks we can as above create more complex behaviours if we need.