LoginSignup
0
0

zustand

Posted at

zustandとは

ZustandはReactのための軽量でシンプルな状態管理ライブラリ

set up

npm install zustand

使い方

storeの作成

import create from 'zustand'

// カウンターストアの定義
const useCounterStore = create(set => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 })),
  decrement: () => set(state => ({ count: state.count - 1 })),
}))

コンポーネントでのストアの使用

import React from 'react'
import { useCounterStore } from './store' // ストアをインポート

const CounterComponent = () => {
  const { count, increment, decrement } = useCounterStore()
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  )
}

export default CounterComponent

globalにならないようにpageごとにstateを管理する。
子コンポーネントへのstateの受け渡しはContext APIを使用する

Recipes

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