ホームページ  >  記事  >  ウェブフロントエンド  >  ZustandのcreateWithEqualityFnテストケースについて説明しました。

ZustandのcreateWithEqualityFnテストケースについて説明しました。

DDD
DDDオリジナル
2024-09-14 06:26:02221ブラウズ

この記事では、渡すことができる条件と等価関数に基づいて再レンダリングを防止する createWithEqualityFn を検証するために書かれたテスト ケースを理解します。

以下のコードは、basic.test.ts から抜粋したものです

it('uses the store with a selector and equality checker', async () => {
  const useBoundStore = createWithEqualityFn(
    () => ({ item: { value: 0 } }),
    Object.is,
  )
  const { setState } = useBoundStore
  let renderCount = 0

  function Component() {
    // Prevent re-render if new value === 1.
    const item = useBoundStore(
      (s) => s.item,
      (_, newItem) => newItem.value === 1,
    )
    return (
      <div>
        renderCount: {++renderCount}, value: {item.value}
      </div>
    )
  }

  const { findByText } = render(
    <>
      <Component />
    </>,
  )

  await findByText('renderCount: 1, value: 0')

  // This will not cause a re-render.
  act(() => setState({ item: { value: 1 } }))
  await findByText('renderCount: 1, value: 0')

  // This will cause a re-render.
  act(() => setState({ item: { value: 2 } }))
  await findByText('renderCount: 2, value: 2')
})

Zustand はテストのニーズに Vitest を使用しています。上記のコード スニペットを見てみましょう。

createWithEqualityFn を初期化します

const useBoundStore = createWithEqualityFn(
    () => ({ item: { value: 0 } }),
    Object.is,
  )

createWithEqualityFn は state () => で初期化されます。 ({ item: { value: 0 } })、等価関数は Object.is

です。

createWithEqualityFn test case in Zustand explained.

createWithEqualityFn は、createState とdefaultEqualityFn の 2 つの変数を受け入れます。

再レンダリングを防止

// Prevent re-render if new value === 1.
    const item = useBoundStore(
      (s) => s.item,
      (_, newItem) => newItem.value === 1,
    )

useBoundStore は、一致する値に基づいて再レンダリングを防ぐために使用されるセレクターと等価関数を受け入れます。

basic.test の上記の例は、値が 1 の場合に再レンダリングを防ぐために使用されます。

await findByText('renderCount: 1, value: 0')

// This will not cause a re-render.
act(() => setState({ item: { value: 1 } }))
await findByText('renderCount: 1, value: 0')

// This will cause a re-render.
act(() => setState({ item: { value: 2 } }))
await findByText('renderCount: 2, value: 2')

これらのアサーションは、状態の更新によって再レンダリングが発生しないことを検証します。

私たちについて:

Think Throo では、オープンソース プロジェクトからインスピレーションを得たベスト プラクティスを教えるという使命を担っています。

Next.js/React の高度なアーキテクチャ概念を実践してコーディング スキルを 10 倍にし、ベスト プラクティスを学び、実稼働レベルのプロジェクトを構築します。

私たちはオープンソースです — https://github.com/thinkthroo/thinkthroo (スターを付けてください!)

コードベース アーキテクチャに基づいた高度なコースでチームのスキルを向上させます。詳細については、hello@thinkthroo.com までお問い合わせください!

参考文献:

  1. https://github.com/pmndrs/zustand/blob/main/tests/basic.test.tsx#L92

  2. https://vitest.dev/guide/

以上がZustandのcreateWithEqualityFnテストケースについて説明しました。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。