0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VanJSでカスタムフック(Custom Hook)を作ってみた

Posted at

VanJSでReactのカスタムフックのようなものを作ってみました。VanJSの公式としてカスタムフックがあるわけではないですが、作ってみたらできたので共有します。

作成したカスタムフック

カウンターの数字の増減とリセットができるものです。引数に初期値と増減する数値を渡して使用できます。

作成したもの

デモ画面を用意したので、実際の動作を試してみてください。

コード

再利用可能を証明するために、カスタムフックであるuseCounterを2つ宣言しています。handlerで値を変更した時にcount2に影響が無いことが確認できます。

src/main.ts
import van from 'vanjs-core'

import { useCounter } from './useCounter'

const App = () => {
  const { div, p, button } = van.tags

  // 初期値は0、増減の間隔は1
  const [count, handler] = useCounter(0, 1)

  // 初期値は10、増減の間隔は3
  const [count2, handler2] = useCounter(10, 3)

  return div(
    p(count),
    button({ type: 'button', onclick: () => handler.increment() }, 'increment'),
    button({ type: 'button', onclick: () => handler.decrement() }, 'decrement'),
    button({ type: 'button', onclick: () => handler.reset() }, 'reset'),
    p(count2),
    button({ type: 'button', onclick: () => handler2.increment() }, 'increment2'),
    button({ type: 'button', onclick: () => handler2.decrement() }, 'decrement2'),
    button({ type: 'button', onclick: () => handler2.reset() }, 'reset2'),
  )
}

van.add(document.getElementById('app')!, App())

Reactのカスタムフックの関数名はuseから始まる必要がありますが、VanJSはその必要はありません。ただし、何の役割を持つ関数なのか分かりやすくするために、敢えてuseCounterとしています。

src/useCounter.ts
import van from 'vanjs-core'

export const useCounter = (initialCount: number, step: number) => {
  const count = van.state(initialCount)

  // カウントを増やす
  const increment = () => {
    count.val += step
  }

  // カウントを減らす
  const decrement = () => {
    count.val -= step
  }

  // カウントをリセット
  const reset = () => {
    count.val = initialCount
  }

  return [count, { increment, decrement, reset }] as const
}

まとめ

今回はVanJSでカスタムフックを作ってみました。VanJSでもReactのカスタムフックようなものが作成できるので、うまく利用すればロジックの再利用やコンポーネントのコードをシンプルに保つことができると思います。

最後に

GoQSystemでは一緒に働いてくれる仲間を募集中です!

ご興味がある方は以下リンクよりご確認ください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?