admin管理员组

文章数量:1204344

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.

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.

Share Improve this question edited Sep 25, 2022 at 2:31 Vishnu 5468 silver badges15 bronze badges asked Aug 1, 2019 at 8:46 four-eyesfour-eyes 12.4k36 gold badges129 silver badges252 bronze badges 4
  • Have you found the best way to do this? I want to avoid re-rendering multiple child components when using setState – UMR Commented Sep 29, 2021 at 16:01
  • @UMR use the accepted answer. – four-eyes Commented Sep 29, 2021 at 18:08
  • but you forgot to accept an answer...I use combination of React.memo and useReducer @Stophface – UMR Commented Sep 30, 2021 at 2:38
  • @UMR There is an accepted answer with seven Upvotes... The one from Monika Mangal. The answer provided by Alireza HI works too... Look closely. I think what you want to achive is different from what I wanted to do. – four-eyes Commented Sep 30, 2021 at 6:26
Add a comment  | 

5 Answers 5

Reset to default 10

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'})

Using object as the initial value

You can use a javascript object as your value. This way you can put more variables in your object and in one place. So your code would be like below:

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

Then you can update it like this:

setExample({...example,first:'new foobar'})
setExample({...example,second:'new foobar second'})

This type of setting is deconstruct your previous values and is replacing your new values with the old ones.

Using this object you just need to add your new property to the initialize of example and to places which you need to set it.

As a complex example you can reach this link:

React Hooks useState() with Object


Notice (updating the variable)

If you just update it using {first:'new foobar'} and don't include the second in your properties you may loose the old value of second. So use the ...example to have the old value of second.

I would suggest to go for reducer hooks. React official site says if you have complex state rather go for userReducer hook.



const initialState = {
first: 'foo',
second: 'bar'
};

function reducer(state, action) {
  switch (action.type) {
    case 'updateFirst':
      return {...state, first: 'fooBar' };
    case 'updateSecond':
      return {...state, second: 'barfoo' };
    case 'updateBoth':
      return {...state, second: 'barfoo',first: 'fooBar' };
    default:
      throw new Error();
  }
}

function Component() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      {state.first}
      {state.second}
      <button onClick={() => dispatch({type: 'updateFirst'})}>UpdateFirst</button>
      <button onClick={() => dispatch({type: 'updateSecond'})}>UpdateSecond</button>
      <button onClick={() => dispatch({type: 'updateBoth'})}>UpdateBoth</button>
    </>
  );
}


Code : https://codesandbox.io/s/busy-rosalind-9oiow

From React docs: useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.

const initialState = { first: '', second: '' };

function reducer(state, action) {
  switch (action.type) {
    case 'doFirst':
      return {...state, first: 'newFirst' };
    case 'doSecond':
      return {...state, second: 'newSecond' };
    default:
      throw new Error();
  }
}

function Component() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      {state.first}
      {state.second}
      <button onClick={() => dispatch({type: 'doFirst'})}></button>
      <button onClick={() => dispatch({type: 'doSecond'})}></button>
    </>
  );
}

You can make your own hook to do this !

function useMultipleStates() {
    const [first setFirst] = useState('foo');
    const [second, setSecond] = useState('bar');

    const setState = (f, s) => {
        setFirst(f);
        setSecond(s);
    }

    return {
        first,
        second,
        setState,
    }
}

You can adapt this to your needs, but if should give you an idea on how to do it.

本文标签: javascriptUsing React Hooks with more than one KeyValue Pair in State ObjectStack Overflow