1️⃣ hooks 폴더 생성
2️⃣ use-훅이름.js로 파일 생성
3️⃣ use로 시작하는 훅 이름으로 함수(컴포넌트) 생성
👾 BackwardCounter.js
import { useState, useEffect } from 'react';
import Card from './Card';
const BackwardCounter = () => {
const [counter, setCounter] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCounter((prevCounter) => prevCounter - 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <Card>{counter}</Card>;
};
export default BackwardCounter;
👾 ForwardCounter.js
import { useState, useEffect } from 'react';
import Card from './Card';
const ForwardCounter = () => {
const [counter, setCounter] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCounter((prevCounter) => prevCounter + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <Card>{counter}</Card>;
};
export default ForwardCounter;
👾 hooks/use-counter.js
const useCounter = (forwards = true) => {
const [counter, setCounter] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
// forwards가 true일 경우 증가 함수 실행
if (forwards) {
setCounter((prevCounter) => prevCounter + 1);
} else {
setCounter((prevCounter) => prevCounter - 1);
}
}, 1000);
return () => clearInterval(interval);
// forwards를 의존성으로 추가!
}, [forwards]);
// useCounter훅은 state인 counter 반환
return counter;
}
export default useCounter;
👉🏻 로직만 구현하는 것일 뿐 상태를 공유하는 것이 아님
👾 ForwardCounter.js
import Card from './Card';
import useCounter from '../hooks/use-counter';
const ForwardCounter = () => {
// 커스텀 훅 사용
const counter = useCounter(true);
return <Card>{counter}</Card>;
};
export default ForwardCounter;
👾 BackwardCounter.js
import Card from './Card';
import useCounter from '../hooks/use-counter';
const BackwardCounter = () => {
// 커스텀 훅 사용
const counter = useCounter(false);
return <Card>{counter}</Card>;
};
export default BackwardCounter;
[참고] Udemy - React 완벽 가이드 with Redux, Next.js, TypeScript