폼 컴포넌트를 만드는 중이었는데, 폼에서 작성해야 할 항목이 많았다.
이를 모두 state로 관리하려는데, useState 선언 코드만 너무 많아지는 것 같아 하나의 useState로 여러 개의 state를 관리할 방법을 찾아봤다.
방법은 비교적 간단했다. 모든 항목들을 하나의 객체로 관리하는 것!
예를 들어 다음과 같이 관리해야 할 상태가 있다고 했을 때,
function App() {
const [name, setName] = useState('');
const [age, setAge] = useState('');
const [id, setId] = useState('');
const [email, setEmail] = useState('');
const [createdAt, setCreatedAt] = useState('');
const [content, setContent] = useState('');
// ...
}
여러 개의 상태들을 다음처럼 하나로 묶을 수 있다.
function App() {
const [form, setForm] = useState({
name: '',
age: '',
id: '',
email: '',
createdAt: '',
content: '',
});
// ...
}
각 input에 대한 onChange
핸들러는 이렇게 작성할 수 있다.
변화가 생긴 프로퍼티만을 갱신하는 작업이다.
const onChange = e => {
setForm({
...form,
[e.target.name]: e.target.value
});
};