Skip to content

Custom Hooks

Yenowme edited this page Dec 18, 2021 · 1 revision

์ปค์Šคํ…€ ํ›… ์ œ์ž‘

  • ์ปค์Šคํ…€ ํ›…์„ ์ œ์ž‘ํ•ด์„œ ์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” state ์กฐ์ • ๊ด€๋ จ ํ•จ์ˆ˜๋“ค์„ ํ•จ๊ป˜ ๋ฆฌํ„ดํ•ด ์ค‘๋ณต์ ์ธ ์‚ฌ์šฉ์„ ์ค„์ธ๋‹ค.

useInput

import { useState } from "react";

type validatorType = (value: string) => boolean;

const useInput = (
  initialValue: string,
  validator: validatorType = () => true //๊ธฐ๋ณธ validator๋ฅผ true๋กœ ์„ค์ •
) => {
  const [value, setValue] = useState(initialValue);

  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const {
      target: { value },
    } = event;
    if (validator(value)) setValue(value);
    else setValid(false);
  };

  return { value, onChange, setValue };
};

export default useInput;
  • Input ํƒœ๊ทธ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” onChageํ•จ์ˆ˜๋ฅผ ๋ฆฌํ„ดํ•˜๋„๋ก ์„ค์ •
  • validate ํ•จ์ˆ˜๋ฅผ ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ ๋ฐ›์•„์„œ input๊ฐ’์„ ์ œํ•œํ•  ์ˆ˜ ์žˆ๋‹ค.

ํ™œ์šฉ ์˜ˆ์‹œ

export default App(){
  const { value, setValue, onChange } = useInput("hi", (value)=>{value.length>30}));

  return <input value={value} onChange={onChange}><input/>
}
  • ์ด์ œ ๋”ฐ๋กœ onChange๋ฅผ ๋งŒ๋“ค์–ด์ค„ ํ•„์š”๊ฐ€ ์—†๋‹ค.
Clone this wiki locally