useReducer로 +1, -1 카운터 만들기
INCREMENT·DECREMENT 액션을 처리하는 reducer를 useReducer에 넘겨 +1, -1 버튼으로 숫자를 바꾸는 카운터를 만들었습니다.
1분 읽기#React
2023년에 쓴 글이라 지금과 다른 내용이 있을 수 있습니다.
useReducer를 사용해 보려고 간단하게 -1, +1 버튼을 구현해 봤다.
javascript
import React, { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
return state;
}
}
function Counter() {
const [number, dispatch] = useReducer(reducer, 0);
const onIncrease = () => {
dispatch({ type: "INCREMENT" });
};
const onDecrease = () => {
dispatch({ type: "DECREMENT" });
};
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-11</button>
</div>
);
}
export default Counter;같은 주제의 글
스켈레톤 로딩 UI를 어디에, 언제 보여 줄지 정한 기준
스켈레톤 UI를 전체 화면과 일부 영역으로 나눠 적용한 기준, Suspense와 MUI Skeleton으로 만든 부분 로딩, 짧은 로딩에는 스켈레톤을 숨기는 지연 컴포넌트와 이미지용 공통 컴포넌트를 정리했습니다.
Recoil 훅 정리: useRecoilState부터 스냅샷까지
useRecoilState·useRecoilValue·useResetRecoilState와 selector의 set, useRecoilSnapshot·useRecoilTransactionObserver·useRecoilCallback으로 스냅샷을 다루는 법을 정리했습니다.
4분 읽기#ReactSWR suspense 옵션으로 로딩 삼항 연산자 걷어내기
SWRConfig에 suspense: true를 켜고 React Suspense의 fallback으로 로딩 UI를 맡기는 방법을 정리했습니다. React Query도 같은 방식으로 씁니다.