- Custom hook
- 리액트에 정의되어있지 않은 나만의 Hook을 만들어 사용하는 것
- 코드가 훨씬 직관적이고 간결해짐
- 유지보수가 훨씬 편리
import { useState } from "react";
function App() {
const [click1, setState1] = useState(false);
const toggle1 = () => setState1((click1) => !click1);
const [click2, setState2] = useState(false);
const toggle2 = () => setState2((click2) => !click2);
const [click3, setState3] = useState(false);
const toggle3 = () => setState3((click3) => !click3);
const [click4, setState4] = useState(false);
const toggle4 = () => setState4((click4) => !click4);
const [click5, setState5] = useState(false);
const toggle5 = () => setState5((click5) => !click5);
return (
<>
<button onClick={toggle1}>{click1 ? "Hello" : "Goodbye"}</button>
<button onClick={toggle2}>{click2 ? "Hello" : "Goodbye"}</button>
<button onClick={toggle3}>{click3 ? "Hello" : "Goodbye"}</button>
<button onClick={toggle4}>{click4 ? "Hello" : "Goodbye"}</button>
<button onClick={toggle5}>{click5 ? "Hello" : "Goodbye"}</button>
</>
);
}
export default App;
버튼을 클릭하면, state가 반전되는 역할을 수행하는 setter 함수
import { useState } from "react";
function App() {
const [click1, setClick1] = useToggle();
const [click2, setClick2] = useToggle();
const [click3, setClick3] = useToggle();
const [click4, setClick4] = useToggle();
const [click5, setClick5] = useToggle();
return (
<>
<button onClick={setClick1}>{click1 ? "Hello" : "Goodbye"}</button>
<button onClick={setClick2}>{click2 ? "Hello" : "Goodbye"}</button>
<button onClick={setClick3}>{click3 ? "Hello" : "Goodbye"}</button>
<button onClick={setClick4}>{click4 ? "Hello" : "Goodbye"}</button>
<button onClick={setClick5}>{click5 ? "Hello" : "Goodbye"}</button>
</>
);
}
const useToggle = (initialState = false) => {
const [state, setState] = useState(initialState);
const toggle = () => setState((state) => !state);
return [state, toggle];
};
export default App;
useToggle 이라는 Hook 덕분에 코드가 훨씬 직관적이고 간결