DEV Community


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

ipavlenko profile image
Igor Pavlenko Author

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

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 Author • 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

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.