I am trying to understand which way of using useState hook is a better practise. Please consider these two examples of a simple React component:
multiple useState hooks
const Cake = () => { const [topping, setTopping] = useState(''); const [icing, setIcing] = useState(''); const [fruit, setFruit] = useState(''); const [base, setBase] = useState(''); const [cake, setCake] = useState({topping: '', icing: '', fruit: '', base: ''}); const createCake = () => { setCake({ topping: topping, icing: icing, fruit: fruit, base: base }); console.log(cake); } return ( <div> <p>Choose from possible toppings:</p> <Select options={toppings} onChange={e => setTopping(e.target.value)} value={topping}/> <p>Choose from possible icings:</p> <Select options={icings} onChange={e => setIcing(e.target.value)} value={icing}/> <p>Choose from possible fruits:</p> <Select options={fruits} onChange={e => setFruit(e.target.value)} value={fruit}/> <p>Choose from possible bases:</p> <Select options={bases} onChange={e => setBase(e.target.value)} value={base}/> <button onClick={createCake}>Create</button> </div> ); } export default Cake;
One useState hook, but all properties of a whole object are updated multiple times
import React, {useState} from 'react';
const Cake = () => { const [cake, setCake] = useState({topping: '', icing: '', fruit: '', base: ''}); const setTopping = (e) => { setCake({ topping: e.target.value, icing: cake.icing, fruit: cake.fruit, base: cake.base }); }; const setIcing = (e) => { setCake({ topping: cake.topping, icing: e.target.value, fruit: cake.fruit, base: cake.base }); }; const setBase = (e) => { setCake({ topping: cake.topping, icing: cake.icing, fruit: cake.fruit, base: e.target.value }); }; const setFruit = (e) => { setCake({ topping: cake.topping, icing: cake.icing, fruit: e.target.value base: cake.base }); }; const createCake = () => { console.log(cake); }; return ( <div> <p>Choose from possible toppings:</p> <Select options={toppings} onChange={setTopping}/> <p>Choose from possible icings:</p> <Select options={icings} onChange={setIcing} value={icing}/> <p>Choose from possible fruits:</p> <Select options={fruits} onChange={setFruit} value={fruit}/> <p>Choose from possible bases:</p> <Select options={bases} onChange={setBase} value={base}/> <button onClick={createCake}>Create</button> </div> ); } export default Cake;
Which of this option would be consider as a better one? Are there any mistakes/bad pracices here that I should avoid in the future?