aotoyae

[React] Custom Hooks : 훅 만들기 본문

React

[React] Custom Hooks : 훅 만들기

aotoyae 2024. 2. 20. 01:10

 

 

💡 Custom Hooks 을 사용해 보자.

 

기존 input 값을 받아오던 방식

import { useState } from "react";

function App() {
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");

  const onChangeName = (e) => { // 패스워드 관리 함수와 똑같이 생겼다
    setName(e.targe.value);
  };

  const onChangePassword = (e) => { // 네임 관리 함수와 똑같이 생겼다
    setPassword(e.targe.value);
  };

  return (
    <div>
      <h2>Custom Hooks</h2>
      <input type="text" value={name} onChange={onChangeName} />
      <input type="password" value={password} onChange={onChangePassword} />
    </div>
  );
}

export default App;

 

반복되는 함수들을 정리할 우리만의 Hook 을 만들어보자!

 

 

hooks 폴더 내 useInput.js 생성

import { useState } from "react";

export const useInput = () => {
  const [value, setValue] = useState(""); // App.jsx 에서 쓰던 useState 를 여기서 쓴다.

  const handler = (e) => {
    setValue(e.target.value);
  };

  return [value, handler];
};

 

App.jsx

import "./App.css";
import { useInput } from "./hooks/useInput";

function App() {
  const [name, onChangeName] = useInput();
  const [password, onChangePassword] = useInput();

  return (
    <div>
      <h2>Custom Hooks</h2>
      <input type="text" value={name} onChange={onChangeName} />
      <input type="password" value={password} onChange={onChangePassword} />
    </div>
  );
}

export default App;

 

반복되는 함수를 아예 없앨 수 있다!

 

~ 활용 ~

** value = id, handler = setId, resetInput = setId 인 것 ~

useInput.jsx

import { useState } from "react";

export const useInput = (initialState = "") => {
  const [value, setValue] = useState(initialState);

  const handler = (e) => {
    setValue(e.target.value);
  };

  const resetInput = () => {
    setValue(initialState);
  };

  return [value, handler, resetInput];
};

 

Login.jsx

const [pwd, setPwd, resetInput] = useInput();

// ...
// 회원가입 성공 시 실행
resetInput(); // input 값을 초기화한다.