Skip to content
Advertisement

Using React Hooks with more than one Key/Value Pair in State Object

I wonder what the best way is to define more than one key/value pair for the state in a Functional Component.

In a class I would initialithe State like

this.state = {
    first: 'foo',
    second: 'bar'
};

To update the State I call

this.setState({
    first: 'foobar',
    second: 'barfoo'
});

Now with React Hooks I initialize the State like so.

const [first, setfirst] = useState('foo');
const [second, setSecond] = useState('bar');

To update the State I call:

setFirst = 'foobar';
setSecond = 'barfoo';

But, IMHO, that is not ideal. I have to rewrite const [x, setX] = useState(...); everytime I want to add a new key/value pair to the State object. Boilerplate. I further always have to keep in mind the “setter” name of x, which is setX. That will get messy, if the State object grows.

It would be nicer if I could simply call

setState(first: 'foobar', second: 'barfoo');

But I am not sure how to initialize the State object properly/what is the best way to do that.

Advertisement

Answer

You can set the whole object using useState like as follows –

const [stateObj, setStateObj] = useState({first:'foobar', second:'barfoo'});

and then to update the state –

setStateObj({first:'foobarnew', second:'barfoonew'})
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement