반응형
✔ useCounter() Custom Hook 만들기
- src > chapter_07 > useCounter.jsx
import React, { useState } from "react";
function useCounter(initialValue) {
const [count, setCount] = useState(initialValue);
const increaseCount = () => setCount((count) => count + 1);
const decreaseCount = () => setCount((count) => Math.max(count - 1, 0));
return [count, increaseCount, decreaseCount];
}
export default useCounter;
이 코드는 초기 count 값을 파라미터로 받아서 count 라는 이름의 state 를 생성하여 값을 제공하고, count 증가 및 감소를 편리하게 할 수 있도록 함수를 제공하는 Hook 이다.
✔ Accomodate 컴포넌트 만들기
- src > chapter_07 > Accommodate.jsx
import React, { useState, useEffect } from "react";
import useCounter from "./useCounter";
const MAX_CAPACITY = 10;
function Accomodate(props) {
const [isFull, setIsFull] = useState(false);
const [count, increaseCount, decreaseCount] = useCounter(0);
// 의존성 배열이 없는 상태 : 컴포넌트가 mount 된 직후에 호출, 컴포넌트가 update 될 때마다 실행
useEffect(() => {
console.log("=========================");
console.log("useEffect() is called.");
console.log(`isFull: ${isFull}`);
});
// 의존성 배열이 있는 상태 : 컴포넌트가 mount 된 직후에 호출, 이 후 count 값이 바뀔 때마다 호출
useEffect(() => {
setIsFull(count >= MAX_CAPACITY);
console.log(`Current count value: ${count}`);
}, [count]);
return (
<div style={{ padding: 16 }}>
<p>{`총 ${count}명 수용했습니다.`}</p>
<button onClick={increaseCount} disabled={isFull}>
입장
</button>
<button onClick={decreaseCount}>퇴장</button>
{isFull && <p style={{ color: "red" }}>정원이 가득찼습니다.</p>}
</div>
);
}
export default Accomodate;
이 컴포넌트를 사람을 수용하는 시설에서 사용한다고 가정한다.
Accomodate 는 컴포넌트는 앞에서 만든 useCounter Hook 을 사용하여 count 를 관리한다. 최대 count 개수는 MAX_CAPACITY 라는 이름의 상수로 정의되어있고, count 개수가 최대 용량을 초과하면 경고문구가 표시되며 더 이상 입장이 불가능해 진다.
- index.js 수정
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Library from './chapter_03/Library';
import Clock from './chapter_04/Clock';
import CommentList from './chapter_05/CommentList';
import NotificationList from './chapter_06/NotificationList';
import Accomodate from './chapter_07/Accomodate';
ReactDOM.render(
<React.StrictMode>
<Accomodate />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
- npm start
이런 게 만들어진다. 콘솔에는 저런 게 찍힌다.
한명 입장하면 저렇게 된다. 콘솔에 저렇게 찍힌다.
MAX_CAPACITY 를 10으로 설정했기 때문에 10명 가득차면 "정원이 가득찼습니다." 라고 난리난다.
콘솔에 찍힌 거 보면 isFull 이 true 로, ㄹㅇ 가득찬 걸 원래도 알았지만 더 확실히 알 수 있다.
0명 이하로는 내려갈 수 없다.
반응형
'Front > React' 카테고리의 다른 글
[React] 클릭 Event 처리하기 (0) | 2023.04.20 |
---|---|
[React] Event 의 정의 및 Event 다루기 (0) | 2023.04.19 |
[React] Hook 의 규칙과 Custom Hook 만들기 (0) | 2023.04.18 |
[React] Hooks - useMemo(), useCallback(), useRef() (0) | 2023.04.18 |
[React] Hooks - useState(), useEffect() (0) | 2023.04.17 |