useReducer vs useState
발행: (2026년 2월 6일 오전 04:23 GMT+9)
2 min read
원문: Dev.to
Source: Dev.to
useState
const [contactName, setContactName] = useState("");
const [contactImage, setContactImage] = useState(null);
const [contactImageUrl, setContactImageUrl] = useState(null);
function handleImageUpload(e) {
const file = e.target.files[0];
const fileName = e.targe.files[0].name;
if (!file) return;
const matchRgx = fileName.match(/\.(jpg|png|jpeg)/);
if (matchRgx != null) {
setContactImageUrl(URL.createObjectURL(e.target.files[0]));
} else {
setContactImage(null);
setContactImageUrl(null);
}
}
function handleForm(e) {
e.preventDefault();
window.alert("Successfully added a contact!");
}
return (
Name:
setContactName(e.target.value)}
/>
Image:
Submit
);
useReducer
const initialFormState = { contactName: "", contactImage: null, contactImageUrl: null };
function reducer(state, action) {
if (action.type === "setState") {
return {
...state,
[action.field]: action.value,
};
} else if (action.type === "ImageUpload") {
return {
...state,
contactImage: action.file,
contactImageUrl: action.url,
};
}
return state;
}
const ReducerHook = () => {
const [state, dispatch] = useReducer(reducer, initialFormState);
function handleImageUpload(e) {
const file = e.target.files[0];
const fileName = e.targe.files[0].name;
if (!file) return;
const matchRgx = fileName.match(/\.(jpg|png|jpeg)/);
if (matchRgx != null) {
const imageUrl = URL.createObjectURL(e.target.files[0]);
dispatch({
type: "ImageUpload",
file: e.target.files[0],
url: imageUrl,
});
} else {
dispatch({
type: "ImageUpload",
file: null,
url: null,
});
}
}
function handleName(e) {
e.preventDefault();
}
return (
Name:
{
dispatch({
type: "setState",
field: e.target.name,
value: e.target.value,
});
}}
/>
Image:
Submit
);
};
export default ReducerHook;
설명
useState 훅을 사용할 때는 관리하고자 하는 각각의 상태에 대해 별도의 setter 함수(예: setContactName)를 정의합니다.
useReducer 를 사용하면 모든 상태 업데이트가 하나의 dispatch 함수에 의해 공유됩니다. dispatch는 액션을 리듀서 함수에 전달하고, 리듀서는 액션 타입에 따라 상태를 어떻게 업데이트할지 결정합니다.
const [state, dispatch] = useReducer(reducer, initialState);
- state – 추적되는 모든 값을 포함하는 객체.
- dispatch – 액션을 리듀서에 보내는 함수.
- reducer – 현재 상태와 액션을 받아 새로운 상태를 반환하는 순수 함수.
- initialState – 상태 객체의 초기값.