2024/06/20 Custom Hooks

YIS·2024년 6월 20일
post-thumbnail

Custom Hooks?

  • 재사용 가능한 기능을 만드는 방법
    기존의 리액트 훅을 조합하거나 새로운 기능을 만들어내어 컴포넌트 간에 공유
    코드의 재사용성을 높이고 복잡한 로직을 캡슐화



커스텀 훅의 특징

1. 이름 규칙

  • 커스텀 훅의 이름은 일반적으로 "use"로 시작하는 것이 관행
    ex) "useCounter", "useModal"

2. 상태 관리

  • 상태 관리, 이벤트 핸들링, 데이터 가져오기 등의 로직을 캡슐화할 수 있음.
    이를 통해 여러 컴포넌트에서 동일한 로직을 재사용 가능.

3. 반환 값

  • 커스텀 훅은 배열이나 객체 형태로 값을 반환할 수 있습니다.
    이를 통해 컴포넌트에서 필요한 값을 쉽게 활용할 수 있습니다.

4. 의존성 관리

  • 커스텀 훅 내부에서 사용되는 의존성(useEffect, useState 등)은 적절히 관리하여,
    이를 통해 불필요한 재렌더링을 방지



예시

import { useState } from 'react';

function useCommentInput() {
  const [comment, setComment] = useState('');

  const handleCommentChange = (event) => {
    setComment(event.target.value);
  };

  const handleCommentSubmit = (event) => {
    event.preventDefault();
    // 여기서 댓글 등록 로직 추가
    console.log('댓글 내용:', comment);
    setComment('');
  };

  return [comment, handleCommentChange, handleCommentSubmit];
}

export default useCommentInput;

이 커스텀 훅 useCommentInput을 다음과 같이 사용

import useCommentInput from './useCommentInput';

function CommentSection() {
  const [comment, handleCommentChange, handleCommentSubmit] = useCommentInput();

  return (
    <form onSubmit={handleCommentSubmit}>
      <input
        type="text"
        value={comment}
        onChange={handleCommentChange}
        placeholder="댓글을 입력하세요"
      />
      <button type="submit">등록</button>
    </form>
  );
}

export default CommentSection;
profile
엉덩이가 무거운 사람

0개의 댓글