React Custom hook

nubim·2025년 2월 21일
  • 커스텀 훅의 규칙
    • 함수명이 반드시 ‘use’로 시작한다
      • useCount라는 네이밍으로 인한 더 명확한 가독성 (네이밍의 중요성)
    • use를 통해 커스텀 훅인지 확인 가능

커스텀 훅으로 얻는 이점

  • 컴포넌트와 기능을 분리 가능
    • 커스텀 훅으로 손쉽게 컴포넌트 간 중복되는 로직을 분리 가능
    • 용이한 확장성, 컴포넌트를 건드리지 않고 기능 추가 가능
const useCount = () => {
  const [count, setCount] = useState(0);
  
  // 컴포넌트를 건드리지 않고 다음과 같이 디버깅용 콘솔 기능을 추가 가능
  useEffect(() => {
	  consolog('count is changed to ', count);
  }, [count])
  
  return [count, setCount];
};

const Component = () => {
  const [count, setCount] = useCount();

  return (
    <div>
      {count}
      <button onClick={() => setCount((c) => c + 1)}>+1</button>
    </div>
  );
};
#1
// 2번째 클릭 시 동일한 값이기에 베일아웃 된다
// 베일아웃(bailout): 리렌더링을 발생시키지 않는 것
const Component = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      {count}
      <button onClick={() => setCount(1)}>
        Set Count to 1
      </button>
    </div>
  );
};

#2
// 2번째 클릭 시 리렌더링 되지만 **화면상 차이는 없다**
// { count: 1 }이라는 새로운 객체가 생성되는데 이 객체가 이전과 동일하지 않기에 리렌더링 유발
const Component = () => {
  const [state, setState] = useState({ count: 0 });

  return (
    <div>
      {state.count}
      <button onClick={() => setState({ count: 1 })}>
        Set Count to 1
      </button>
    </div>
  );
};

#3
// Bad
// 클릭해도 리렌더링되지 않는다, 객체가 변하지 않았기 때문
const Component = () => {
  const [state, setState] = useState({ count: 0 });

  return (
    <div>
      {state.count}
			<button 
				onClick={() => { state.count = 1; setState(state); }
			>
				Set Count to 1
      </button>
    </div>
  );
};

#4
// 작동은 하지만 더블클릭을 빠르게 할 경우 한 번만 증가한다
// 클릭 횟수와 동일하게 '함수형 상태 갱신' 필요
const Component = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      {count}
      <button onClick={() => setCount(count + 1)}>
        Set Count to {count + 1}
      </button>
    </div>
  );
};

#5
// Good
// 함수형 상태 갱신
// 클릭횟수와 동일하게 작동, 원리는 이전 값을 참조함으로 최신값을 참조하기때문
<button onClick={() => setCount((c) => c + 1)>

#6
// 함수형 상태 갱신도 베일아웃이 가능하다
// 조건문에서 짝수일 때 setState((c) => c)를 호출할 경우
// 이전과 객체가 같아서 setState를 쓰더라도 리렌더링이 유발되지 않는다

<button onClick={() => setCount((c) => c % 2 === 0 ? 0 : c + 1)}>
  Set Count
</button>

Ref

0개의 댓글