Custom useState

YEONGHUN KO·2022년 2월 17일
0

REACT JS - BASIC

목록 보기
10/30
post-thumbnail
  • useState를 이용해 커스텀 함수를 만들어 함수컴포넌트 안에서 state를 간략화 할 수 있다.
// useInputState.js
export default initVal => {
  const [value,setValue] = useState(initVal)

  const handleChange = (e) => {
    updateEmail(e.target.value)
  }

  const reset = () => {
    setValue('')
  }

  return [value, handleChange, reset];
}

// SimpleHook.js
export default function SimpleFormInputHook() {
  const [email, updateEmail, resetEmail] = useInputState("");
  const [password, updatePassword, resetPassword] = useInputState("");
  return (
    <div>
      <h1>
        Email is: {email} & Password is: {password}
      </h1>
      <input type='text' value={email} onChange={updateEmail} />
      <input type='text' value={password} onChange={updatePassword} />
      <button onClick={resetEmail}>Reset Email</button>
      <button onClick={resetPassword}>Reset Password</button>
    </div>
  );
}

useInputState를 통해서 state를 더욱더 간단하게 사용할 수 있게 되었다.

profile
'과연 이게 최선일까?' 끊임없이 생각하기

0개의 댓글