ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1-11 custom hooks
    React 심화주차 2023. 5. 16. 20:39

    같은 useState를 이용해서 input창을 관리하는 중복되는 코드가 너무 많다면 관리가 힘들어질 수 있다.
    그래서 customhooks를 이용해서 정리해놓는 방법을 알아보자. 

    useInput이라는 customhooks 만들기

    src폴더에 hooks라는 폴더만들고 useInput.js파일 만들기

    useState를 import해와서
    input창의 공통된 동작 로직을 useInput이라는 이름의 함수로 만든다.

    import { useState } from "react";
    
    const useInput = () => {
      // state
      const [value, setValue] = useState("");
    
      // handler
      const handler = (e) => {
        setValue(e.target.value);
      };
    
      return [value, handler];
    };
    
    export default useInput;

     

    내보내고 App.jsx에서 useInput을 import한 후,
    곧바로 useInput을 useState처럼 만든다.

    import "./App.css";
    // import { useState } from "react";
    import useInput from "./hooks/useInput";
    
    function App() {
      const [name, onChangeNameHandler] = useInput();
      const [password, onChangePasswordHandler] = useInput();
    
      // const [name, setName] = useState("");
      // const [password, setPassword] = useState("");
    
      // const onChangeNameHandler = (e) => {
      //   setName(e.target.value);
      // };
      // const onChangePasswordHandler = (e) => {
      //   setPassword(e.target.value);
      // };
    
      return (
        <div>
          <input type="text" value={name} onChange={onChangeNameHandler} />
          <input type="text" value={password} onChange={onChangePasswordHandler} />
        </div>
      );
    }
    
    export default App;


    한결 간결해졌다.
    이처럼 custom hooks를 많이 연구해보고 잘 사용하면 유지보수 측면에서 많은 도움이 된다.


    'React 심화주차' 카테고리의 다른 글

    1-13 react query (2)  (0) 2023.05.17
    1-12 react query (1)  (0) 2023.05.17
    1-10 thunk 심화  (0) 2023.05.16
    1-9 thunk 소개 및 기초 실습  (0) 2023.05.16
    1-8 axios interceptor  (0) 2023.05.16
Designed by Tistory.