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?

ref / reactive / store の使い分けを整理する(Vue / Nuxt)

0
Posted at

1. はじめに

Vue / Nuxtで開発している際、状態管理でこんな悩みが出てきました。

  • refでいいのか?
  • reactiveを使うべき?
  • それともstore(Pinia)?

この記事では、実務目線で
ref / reactive / store の使い分けを整理します。

2. 結論(先に)

まず結論です。

  • ref:単一の値
  • reactive:オブジェクト
  • store:複数コンポーネントで共有する状態

3. ref の使いどころ

■ 基本

const count = ref(0)

■ 向いているケース

  • 数値 / 文字列 / boolean
  • 単純な状態
  • コンポーネント内だけで完結する

■ 実務例

const isOpen = ref(false)
const loading = ref(true)

UI状態はほぼrefでOK

■ 注意点

count.value++

.value を忘れがち

4. reactive の使いどころ

■ 基本

const user = reactive({
  name: '',
  age: 0
})

■ 向いているケース

  • フォーム
  • オブジェクト構造の状態
  • ネストしたデータ

■ 実務例

const form = reactive({
  name: '',
  email: '',
  password: ''
})

■ refとの違い

項目 ref reactive
単一値 ◎ △
オブジェクト △ ◎
.value 必要 不要

■ 注意点

const user = reactive({ name: 'A' })

// NG(リアクティブが壊れる)
user = { name: 'B' }

再代入すると壊れる

5. store(Pinia)の使いどころ

■ 基本

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null
  })
})

■ 向いているケース

  • ログイン情報
  • 設定情報
  • 複数ページで共有する状態

■ 実務例

const userStore = useUserStore()
userStore.user = { name: 'Taro' }

6. よくある間違い

とりあえずstoreに入れる

  • 依存が増える
  • 変更の影響範囲が広がる
  • デバッグしにくい

reactiveを多用する

オブジェクト以外では不要

refで全部持つ

const userName = ref('')
const userAge = ref(0)

バラバラになって管理しづらい

7. 使い分けの指針(実務版)

■ スコープで考える

スコープ 手段
コンポーネント内 ref / reactive
ページ内共有 composable
アプリ全体 store

■ データ構造で考える

データ 手段
単一値 ref
オブジェクト reactive
グローバル store

8. 実務での使用パターン

  • UI状態 → ref
  • フォーム → reactive
  • ユーザー情報 → store

9. まとめ

ref / reactive / store の使い分けは、

「データの種類」と「スコープ」で決める

これが一番シンプルです。

0
0
1

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?