230710 Custom Hooks

๋‚˜์œค๋นˆยท2023๋…„ 7์›” 10์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
17/55

๐Ÿ“Œ Custom Hooks

Custom Hooks ์™œ ์“ฐ๋Š”๊ฐ€?
์•„๋ž˜์˜ ์˜ˆ์‹œ์ฒ˜๋Ÿผ ๋ฐ˜๋ณต๋˜๋Š” ๋กœ์ง์ด๋‚˜ ์ค‘๋ณต๋˜๋Š” ์ฝ”๋“œ๋ฅผ ์šฐ๋ฆฌ๋งŒ์˜ ํ›…์œผ๋กœ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค!

์˜ˆ์‹œ

import "./App.css";
import { useState } from "react";

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

  const onChangeNameHandler = (event) => {
    setName(event.target.value);
  };

  const onChangePasswordHandler = (event) => {
    setPassword(event.target.value);
  };

  return (
    <div>
      <input type="name" value={name} onChange={onChangeNameHandler} />
      <input
        type="password"
        value={password}
        onChange={onChangePasswordHandler}
      />
    </div>
  );
}

export default App;

๐Ÿ“Œ Custom Hooks ๋งŒ๋“ค๊ธฐ

1) ํด๋”๊ตฌ์กฐ

2) useInput.js ์ƒ์„ฑ ๋ฐ hook ๋งŒ๋“ค๊ธฐ

import { useState } from "react";

const useInput = () => {
  // state
  const [value, setValue] = useState("");

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

  // return
  return [value, handler];
};

export default useInput;

3) App.jsx ์ปดํฌ๋„ŒํŠธ์—์„œ useInput ์‚ฌ์šฉํ•˜๊ธฐ

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

function App() {
  const [name, onChangeNameHandler] = useInput();
  const [password, onChangePasswordHandler] = useInput();

  // const [name, setName] = useState("");
  // const [password, setPassword] = useState("");

  // const onChangeNameHandler = (event) => {
  //   setName(event.target.value);
  // };

  // const onChangePasswordHandler = (event) => {
  //   setPassword(event.target.value);
  // };

  return (
    <div>
      <input type="name" value={name} onChange={onChangeNameHandler} />
      <input
        type="password"
        value={password}
        onChange={onChangePasswordHandler}
      />
    </div>
  );
}

export default App;
profile
ํ”„๋ก ํŠธ์—”๋“œ ๊ฐœ๋ฐœ์ž๋ฅผ ๊ฟˆ๊พธ๋Š”

0๊ฐœ์˜ ๋Œ“๊ธ€