DEV Community

Hihi
Hihi

Posted on • Edited on

`useState` and `prevState`

There's a way to update your React state more efficiently using the prevState with a callback in setState function.

const [name, setName] = useState('');
const [address, setAddress] = useState('');
const [phone, setPhone] = useState('');

// we have to update them separately in handlers
const handleNameChange = (arg) => setName(arg);
const handleAddressChange = (arg) => setAddress(arg);
const handlePhoneChange = (arg) => setPhone(arg);
Enter fullscreen mode Exit fullscreen mode

In the above case, if we have more fields that means the handlers will grow in a repetitive way. To solve this problem, I have a clever way to nest them in an object and make use of prevState in setState.

const [formData, setFormData] = useState({});

const handler = (formProps) => (newValue)
 => setFormData(prevState => 
   ({...prevState, [formProps]:newValue})
 );
Enter fullscreen mode Exit fullscreen mode

Top comments (0)