[TIL] custom Hook

yeols·2023년 12월 5일
1

[TIL]

목록 보기
49/72

custom hook 기본 예시

일반적인 React 문법

import { useState } from 'react'

function App() {
  const [count, setCount] = useState(0)

  return (
      <div>
        <p>{count}</p>
        <button onClick={() => setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
      </div>
  );
}

export default App;

custom Hook 작성

import {useState} from "react";

export const useCounter = (initialState = 0) => {
    const [count, setCount] = useState(initialState);

    const handleIncrement = () => setCount(count + 1);
    const handleDecrement = () => setCount(count - 1);

    return {count, handleIncrement, handleDecrement};
}

custom Hook 사용

import {useCounter} from "./hooks/useCounter.jsx";

function App() {
    const {count, handleIncrement, handleDecrement} = useCounter(0);
  return (
      <div>
        <p>{count}</p>
        <button onClick={handleIncrement}>+</button>
        <button onClick={handleDecrement}>-</button>
      </div>
  );
}

export default App;

내가 생각하는 custom hook의 장점

위의 예제는 아주 간단한 카운팅 앱이기에 크게 와닿지 않을 수 있지만
내가 생각하는 custom hook의 장점
1. custom hook내에서 hook을 사용 할 수 있다.

  • 일반 js파일에는 hook을 사용 할 수 없기 때문에 state관리에 용이 하지 않지만 custom hook는 내부에서 자유롭게 hook을 사용 할 수 있다.
  1. 재사용성 용이 하다.
  • 위의 예제에서는 와닿지 않겠지만 재사용성이 아주 좋다. 특히 form내에 input들이 많을때 를 생각해 보면 custom hook으로 간결한 코드를 작성이 가능하다.
profile
흠..

0개의 댓글

관련 채용 정보