use-counter

use-counter

주어진 경계 안에서 state를 증가/감소시키는 use-counter 훅에 대해 설명해 드릴게요. @mantine/hooks 패키지에서 제공돼요.

출처: 문서

본문

사용법

import { Group, Button, Text } from '@mantine/core';
import { useCounter } from '@mantine/hooks';

function Demo() {
  const [count, handlers] = useCounter(0, { min: 0, max: 10 });

  return (
    <>
      <Text>Count: {count}</Text>
      <Group justify="center">
        <Button onClick={handlers.increment}>Increment</Button>
        <Button onClick={handlers.decrement}>Decrement</Button>
        <Button onClick={handlers.reset}>Reset</Button>
        <Button onClick={() => handlers.set(5)}>Set 5</Button>
      </Group>
    </>
  );
}

정의

interface UseCounterOptions {
  min?: number;
  max?: number;
  step?: number;
}

interface UseCounterHandlers {
  increment: () => void;
  decrement: () => void;
  set: (value: number) => void;
  reset: () => void;
}

type UseCounterReturnValue = [number, UseCounterHandlers];

function useCounter(
  initialValue?: number,
  options?: UseCounterOptions,
): UseCounterReturnValue

내보내는 타입

UseCounterOptions, UseCounterHandlers, UseCounterReturnValue 타입은 @mantine/hooks 패키지에서 내보내지므로 애플리케이션에서 import할 수 있어요:

import type { UseCounterOptions, UseCounterHandlers, UseCounterReturnValue } from '@mantine/hooks';

더 알아보기 (Learn more)