React는 너무나도 초보이지만 몇 가지 배운 훅이 있다.
useState, useEffect, useContext
이 중에서 가장 쉽고 자주 사용하는 것만 따지면 useState 이기도 하고, 프로젝트에서 회원가입을 제작하면서 유효성 검증을 진행하며 useState를 진짜 무지막지하게 썼다.
useReducer는 이런 유효성 검사에 가장 적합하게 느껴져서 정리해준 블로그를 보며 내 블로그에도 옮겨적으려 한다.
겸사겸사 다음번 작업 때는 이걸 활용해보기도 하고
아무튼 아래는 코드다.
React 프로젝트 생성 시 자연스럽게 생성되는 App.js
import './App.css';
import Counter from './samples/Counter';
import EditCalendarEvent from './samples/EditCalendarEvent';
function App() {
return (
<div className="App">
<EditCalendarEvent/><br/>
<Counter/>
</div>
);
}
export default App;
App.js에서 호출하는 EditCalendarEvent.js 와 Counter.js
import { useReducer } from "react";
function EditCalendarEvent() {
const [event, updateEvent] = useReducer(
(prev, next) => {
const newEvent = { ...prev, ...next };
// 시작 날짜가 종료 날짜 이후가 될 수 없음을 보장한다
if(newEvent.startDate > newEvent.endDate) {
newEvent.endDate = newEvent.startDate;
}
// 제목이 5자를 넘을 수 없음을 보장합니다
if(newEvent.title.length > 5) {
newEvent.title = newEvent.title.substring(0, 5);
}
return newEvent;
},
{ title: "", description: "", attendees: [] }
);
return (
<>
<input
value={event.title}
onChange={(e) => updateEvent({ title: e.target.value })}
/>
</>
);
}
export default EditCalendarEvent;
import { useReducer } from "react";
function Counter() {
const [count, setCount] = useReducer((prev, next) => Math.min(next, 10), 0);
return <button onClick={() => setCount(count + 1)}>Count is {count}</button>
}
export default Counter;
아래 출처로부터 코드를 그대로 베낀거라 EditCalendarEvent.js는 아직 미완성이다.
EditCalendarEvent.js에서는 input에 글자가 5자를 넘을 수 없게만 설정되어 있고, Counter.js에는 버튼 클릭 counter가 증가하는데 최대 10까지만 증가하게 설정되어 있다.
결론적으로 useState를 사용하면 변수를 최소 2배로 설정해야할텐데 이러한 단점을 많이 줄여주는 것 같다.(물론, 문법이 더 복잡하긴 하지만...)
참고 및 예시는 아래 출처로부터 보고 공부했으며, 훨씬 정리가 잘 되어있다.