[React] Custom Hook이란 ?

현채은·2024년 1월 30일
0
post-thumbnail

Custom Hook이란 ?

: 개발자가 직접 작성하는 Hook으로, 반복되는 로직을 하나로 묶어 컴포넌트로 생성하여 사용하는 것이다.

  • 보통 input과 fetch를 관리할 때 자주 사용된다.

왜 사용해야하나 ?

  • 코드, 로직이 간결해지고 가독성이 좋아진다.
  • 필요없는 반복을 줄이고 재사용성을 높여준다.
  • 수정사항 발생시, 커스텀 훅 내에서 수정하면 되기 때문에 유지보수에 용이하다.

🚨 주의할 점 (⭐️⭐️⭐️⭐️⭐️)

Custom Hook은 값을 재사용하기 위한 것이 아닌 useState와 useEffect와 같이 로직의 재사용을 위한 것이다.
따라서 어느 컴포넌트에서 사용하는가에 따라 값이 유지되는 것이 아닌 새롭게 값이 정해지기 때문에 로직을 재사용하는 의도로 사용해야 한다.

custom hook을 사용하기 전

  • AppSignup.jsx
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>
) ;

custom hook을 사용한 후

  • 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 };
}
  • AppSign.jsx
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>
  );
}

profile
프론트엔드 개발자

0개의 댓글