`useState` and `prevState`

`useState` and `prevState`

·

1 min read

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);

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}
    ));