[React] user Hook

노호준·2023년 9월 5일
0
  • 왜 쓰는가? : 여러 파일에서 재사용, 한 파일이 너무 길어지지 않게 줄여 가독성 상승
  • 어떻게 쓰는가? : 앞에 use를 붙이고 function, return 사이에 원하는 코드작성
//정의
import { useState } from 'react'

function useInput() {
  const [value, setValue] = useState('');
  const onChange = (e) => setValue(e.target.value);
  
  return { value, onChange };
}

export default useInput;
//사용
import useInput from '@/core/useInput';

function MainPage() {

  const username = useInput();
  const password = useInput();
  const email = useInput();
  
  return (
    <main className="container">
      <div className="header">Welcome, 👋</div>
      
      <hr />

      <label htmlFor="username">이름</label>
      <input type="text" id="username" {...username} />

      <hr />

      <label htmlFor="email">이메일</label>
      <input type="email" id="email" {...email} />

      <hr />

      <label htmlFor="password">비밀번호</label>
      <input type="password" id="password" {...password} />

      <hr />

      
    </main>
  );
}

export default MainPage;

0개의 댓글