Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update multiple state at once using react hook react.js

I would like to know if I can use setState hook multiple times in same function. For example, like this

import React, { useEffect, useState } from 'react';

function(props) {
const [color, setColor] = useState(0)
const [size, setSize]= useState(0)
const [weight, setWeight] = useState(0)

const onClickRandomButton = () => {
    setColor(Math.random() * 10)
    setSize(Math.random() * 10)
    setWeight(Math.random() * 10)
}

return <div>
  <button onClick = {onClickRandomButton}>random</button>
</div>

}

I have tested, but it doesn't work as expected. To set multiple values at once using hook, how should I do? Thanks

like image 690
Nomura Nori Avatar asked Feb 28 '20 01:02

Nomura Nori


People also ask

How do you update states with hooks in React?

React calls your component for the first time. React finds a call to useState , creates a new Hook object (with the initial state), changes the current Hook variable to point to this object, adds the object to the Hooks list, and return the array with the initial state and the function to update it.

Can we use multiple useState?

Explanation. As we learned earlier, we can use multiple State or Effect Hooks in a single component: function Form() { // 1. Use the name state variable const [name, setName] = useState('Mary'); // 2.

Can we have multiple useState in React?

Yes, but you might not want to. With class components we would keep all of our state in one object. Then when we changed state with setState , we would provide an object and the API would "merge" its contents into the existing state for us. This doesn't happen with setting state in function components with useState .


1 Answers

You can use one useState with object value for updating the styles at once:

import React, { useEffect, useState } from 'react';

export default function (props) {
  const [style, setStyle] = useState({ color: 0, size: 0, weight: 0 });

  const onClickRandomButton = () => {
    setStyle({
      color: Math.random() * 10,
      size: Math.random() * 10,
      weight: Math.random() * 10,
    });
  };

  return (
    <div>
      <button onClick={onClickRandomButton}>random</button>
    </div>
  );
}

And if in any method you want to update just one property, for example: color, you could do something like this:

...
  const handleEditColor = color => {
    setStyle({
      ...style,
      color
    });
  };
...
like image 127
Hamed Navabian Avatar answered Sep 28 '22 11:09

Hamed Navabian