import { useState } from 'react'
function App() {
const [count, setCount] = useState(0)
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
</div>
);
}
export default App;
import {useState} from "react";
export const useCounter = (initialState = 0) => {
const [count, setCount] = useState(initialState);
const handleIncrement = () => setCount(count + 1);
const handleDecrement = () => setCount(count - 1);
return {count, handleIncrement, handleDecrement};
}
import {useCounter} from "./hooks/useCounter.jsx";
function App() {
const {count, handleIncrement, handleDecrement} = useCounter(0);
return (
<div>
<p>{count}</p>
<button onClick={handleIncrement}>+</button>
<button onClick={handleDecrement}>-</button>
</div>
);
}
export default App;
위의 예제는 아주 간단한 카운팅 앱이기에 크게 와닿지 않을 수 있지만
내가 생각하는 custom hook의 장점
1. custom hook내에서 hook을 사용 할 수 있다.