: 개발자가 직접 작성하는 Hook으로, 반복되는 로직을 하나로 묶어 컴포넌트로 생성하여 사용하는 것이다.
Custom Hook
은 값을 재사용하기 위한 것이 아닌 useState와 useEffect와 같이 로직의 재사용을 위한 것이다.
따라서 어느 컴포넌트에서 사용하는가에 따라 값이 유지되는 것이 아닌 새롭게 값이 정해지기 때문에 로직을 재사용하는 의도로 사용해야 한다.
import React, { useState } from "react";
export default function AppSignup() {
const [id, setId] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = (e) => {
e. preventDefault ();
};
const handleId = (e) => {
setId (e. target.value);
};
const handlePassword = (e) => {
setPassword (e. target. value);
return (
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="id">아이디:</Labet>
<input type="text" id="id" value={id} onChange={handleId} />
<label htmtFor="password">비밀번호:</label>
<input
type="password"
id="password"
value={password}
onChange={handlePassword}
/>
</form>
</div>
) ;
}
hooks 라는 폴더를 생성한 후 use-input이라는 파일을 생성해준다.
use-input.jsx
import { useState } from "react";
export default function useInput({ initialState }) {
const [value, setValue] = useState(initialState);
const onChange = (e) => {
setValue(e.target.value);
};
return { value, onChange };
}
import React from "react";
import useInput from "./hooks/use-input";
export default function AppSignup() {
const id = useInput("");
const password = useInput("");
const handleSubmit = (e) => {
e.preventDefault();
};
return (
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="id">아이디:</label>
<input type="text" id="id" name="id" {...id} />
<label htmlFor="password">비밀번호:</label>
<input type="password" id="password" name="password" {...password} />
</form>
</div>
);
}