- 커스텀 훅의 규칙
- 함수명이 반드시 ‘use’로 시작한다
- useCount라는 네이밍으로 인한 더 명확한 가독성 (네이밍의 중요성)
- use를 통해 커스텀 훅인지 확인 가능
커스텀 훅으로 얻는 이점
- 컴포넌트와 기능을 분리 가능
- 커스텀 훅으로 손쉽게 컴포넌트 간 중복되는 로직을 분리 가능
- 용이한 확장성, 컴포넌트를 건드리지 않고 기능 추가 가능
const useCount = () => {
const [count, setCount] = useState(0);
useEffect(() => {
consolog('count is changed to ', count);
}, [count])
return [count, setCount];
};
const Component = () => {
const [count, setCount] = useCount();
return (
<div>
{count}
<button onClick={() => setCount((c) => c + 1)}>+1</button>
</div>
);
};
#1
const Component = () => {
const [count, setCount] = useState(0);
return (
<div>
{count}
<button onClick={() => setCount(1)}>
Set Count to 1
</button>
</div>
);
};
#2
const Component = () => {
const [state, setState] = useState({ count: 0 });
return (
<div>
{state.count}
<button onClick={() => setState({ count: 1 })}>
Set Count to 1
</button>
</div>
);
};
#3
const Component = () => {
const [state, setState] = useState({ count: 0 });
return (
<div>
{state.count}
<button
onClick={() => { state.count = 1; setState(state); }
>
Set Count to 1
</button>
</div>
);
};
#4
const Component = () => {
const [count, setCount] = useState(0);
return (
<div>
{count}
<button onClick={() => setCount(count + 1)}>
Set Count to {count + 1}
</button>
</div>
);
};
#5
<button onClick={() => setCount((c) => c + 1)>
#6
<button onClick={() => setCount((c) => c % 2 === 0 ? 0 : c + 1)}>
Set Count
</button>
Ref