C
C
cosonicsq2020-04-18 20:56:59
React
cosonicsq, 2020-04-18 20:56:59

How to write a useState hook if the state has multiple properties?

There is a class component that needs to be converted into a functional one and the state should be converted into the useState hook. But state has several properties:

class App extends React.Component {

  state = {
    num: 0,
    text: 'no',
    textUpper: 'HELLO'
  }

  changeState = () => {
    this.setState({
      num: this.state.num + 1,
      text: "yes",
      textUpper: 'BYE'
    });
  }
  
  render() {
    return (
      <div>
          <button onClick={this.changeState}>like</button>
          {this.state.num}
          {this.state.text}
          {this.state.textUpper}
      </div>
    );
  }
}


If there was only one property, then I know how to redo it:

const App = () => {
      const [num, setNum] = useState(0);

      const changeState = () => {
           setNum(num+1);
       }
  
    return (
      <div>
            <button onClick={changeState}>like</button>
           {num}
      </div>
    );
}


But how to remake my component when there are several properties, as in my case, I don’t know. Tell me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tigran Abrahamyan, 2020-04-18
@cosonicsq

No matter how many variables, we use useState an infinite number of times.

const [num, setNum] = useState(0);
const [text, setText] = useState('no');
const [textUpper, setТextUpper] = useState('HELLO');

const changeState = () => {
  setNum(num + 1);
  setText('yes');
  setТextUpper('BYE');
}

Or we can create an object
const [data, setData] = useState({
  num: 0,
  text: 'no',
  textUpper: 'HELLO'
});

Or we can use useReducer .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question