TIL34. Custom Hooks

김정현·2020년 11월 29일
1

Custom Hooks

custom hooks 사용하지않은 소스

import React, { useState, useEffect } from "react";

export default function App() {
  const [word, setWord] = useState();
  const [title, setTitle] = useState('init title');
  useEffect(() => {
    document.title = title;
  }, [title])

  return (
    <div className="App">
      <h1>Title Changer</h1>
      <h2>변경된 타이틀은 {title}</h2>
      <input placeholder="input here" onChange={(e) => setWord(e.target.value)}/>
      <button onClick={() => setTitle(word)}>Change</button>
    </div>
  );
}

custom hooks 사용한 소스

import React, { useState, useEffect } from "react";

const useTitle = init => {
  const [word, setWord] = useState();
  const [title, setTitle] = useState(init);

  const onChange = e => {
    const {
      target: { value }
    } = e;

    if (value) {
      setWord(value);
    }
  };

  const onClick = () => {
    setTitle(word);
  }

  useEffect(() => {
    document.title = title;
  }, [title]);

  return { title, onChange, onClick };
};

export default function App() {
  const title = useTitle("init title");
  return (
    <div className="App">
      <h1>Title Changer</h1>
      <h2>변경된 타이틀은 {title.title}</h2>
      <input placeholder="input here" onChange={title.onChange}/>
      <button onClick={title.onClick}>Change</button>
    </div>
  );
}

오히려 Custom hook의 코드량이 많아보일 수 있겠지만, 이를 모듈로 하여 필요한 다른 곳에서도 재사용이 가능하다는 장점이 있다.

그럴 때는 모듈을 불러오고 호출하는 것 만으로 코드량을 줄일 수 있다.

import useTitle from 'path';

const title = useTitle("init title");
  • 컴포넌트와 로직을 분리할 수 있습니다.
  • 컴포넌트와 로직을 조합하는 형태로 작성할 수 있습니다.
  • 여러 컴포넌트에서 재활용이 가능하기 때문에 중복 코드를 줄일 수 있습니다.
  • 여러 React 프로젝트를 진행한다면 효용성 좋은 Custom Hooks를 공유하며 기술적 경험을 축적할 수 있습니다.

0개의 댓글