๐ Custom Hooks
Custom Hooks ์ ์ฐ๋๊ฐ?
์๋์ ์์์ฒ๋ผ ๋ฐ๋ณต๋๋ ๋ก์ง์ด๋ ์ค๋ณต๋๋ ์ฝ๋๋ฅผ ์ฐ๋ฆฌ๋ง์ ํ
์ผ๋ก ๊ด๋ฆฌํ ์ ์๋ค!
์์
import "./App.css";
import { useState } from "react";
function App() {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
const onChangeNameHandler = (event) => {
setName(event.target.value);
};
const onChangePasswordHandler = (event) => {
setPassword(event.target.value);
};
return (
<div>
<input type="name" value={name} onChange={onChangeNameHandler} />
<input
type="password"
value={password}
onChange={onChangePasswordHandler}
/>
</div>
);
}
export default App;
๐ Custom Hooks ๋ง๋ค๊ธฐ
1) ํด๋๊ตฌ์กฐ
2) useInput.js ์์ฑ ๋ฐ hook ๋ง๋ค๊ธฐ
import { useState } from "react";
const useInput = () => {
// state
const [value, setValue] = useState("");
// handler
const handler = (event) => {
setValue(event.target.value);
};
// return
return [value, handler];
};
export default useInput;
3) App.jsx ์ปดํฌ๋ํธ์์ useInput ์ฌ์ฉํ๊ธฐ
import "./App.css";
import useInput from "./hooks/useinput";
// import { useState } from "react";
function App() {
const [name, onChangeNameHandler] = useInput();
const [password, onChangePasswordHandler] = useInput();
// const [name, setName] = useState("");
// const [password, setPassword] = useState("");
// const onChangeNameHandler = (event) => {
// setName(event.target.value);
// };
// const onChangePasswordHandler = (event) => {
// setPassword(event.target.value);
// };
return (
<div>
<input type="name" value={name} onChange={onChangeNameHandler} />
<input
type="password"
value={password}
onChange={onChangePasswordHandler}
/>
</div>
);
}
export default App;