简体   繁体   中英

How to use useState hook in React correctly?

I am a little bit confused with using useState() hook in React. I want to store some data in component state, for example values from form - name, minValue and maxValue. What my code should look like?

const [state, setState] = useState({
   name: '',
   minValue: 0,
   maxValue: 9
});

or

const [name, setName] = useState('');
const [minValue, setMinValue] = useState(0);
const [maxValue, setMaxValue] = useState(9);

Is any of these approaches better or are they equal?

While both will work, I would consider the second one to be better, since it is easier to read and update. If you want to handle more complex objects, take a look at useReducer() .

The useState() returns your current state value and a method to update this state value. There you can set any kind of object, array or string etc. Like this:

const [someState, setSomeState] = useState('something')                                    

To manipulate the state you have to call a function like so:

const someFunction = () => { setSomeState('new state') }                                              

Hope that helpes.

Both will work but, you can use this approach if you have many state variable because it reduces your code

const [state, setState] = useState({
       name: '',
       minValue: 0,
       maxValue: 9
    });

    setState(prevData => ({
              ...prevData,
              name: value
              minValue: value
            }))

you can use this approach if you have less state variable and it is easier to manage

const [name, setName] = useState('');
const [minValue, setMinValue] = useState(0);
const [maxValue, setMaxValue] = useState(9);

setName(value);
setMinValue(value);
setMaxValue(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM