Nuxt3移行 Vuex→composablesで2週間短縮した方法
この記事で解決すること
Nuxt3への移行時、Vuexからcomposablesへの置き換えを検討しているが、どこまでを状態として管理し、どのような粒度でcomposablesを分割するか判断に迷うことがあります。特に中規模以上のアプリケーションでは、単純にVuexのstoreをcomposablesに変換するだけでは、かえって保守性が悪化する場面も出てきます。
この記事では、Vuexからcomposablesへの移行時に必要な設計判断と、実装時の具体的なアプローチを整理します。
なぜこの問題は起きるのか
Vuexとcomposablesは、状態管理における役割分担の考え方が根本的に異なります。Vuexはアプリケーション全体の状態を一元管理する思想ですが、composablesは関心事ごとに分散させる思想です。
この思想の違いを理解せずに移行すると、いくつかの問題が生じることがあります。Vuexのmodule構造をそのままcomposablesに変換してしまい、結果として巨大なcomposableが生まれてしまう。あるいは逆に、細かく分割しすぎて状態の依存関係が見えにくくなる。
移行の難しさは技術的な変換作業ではなく、状態管理の設計思想を見直すことにあると考えています。
解決のための考え方
移行を成功させるには、まず現在のVuexで管理している状態を3つの観点で分類することから始まります。
1つ目は「本当にグローバルな状態管理が必要な状態」の識別。認証情報やアプリケーション設定など、複数のコンポーネント間で共有が必要な状態です。2つ目は「コンポーネント間の一時的なデータ受け渡し」で管理されている状態。これらはpropsやemitでの解決を検討できます。3つ目は「サーバーから取得したデータのキャッシュ」として管理されている状態で、これは別の仕組みでの管理が適している場合があります。
この分類を行うことで、composablesでの管理対象が明確になります。その上で、composablesの粒度は「関心事の境界」で決めることを意識しています。
ここから先は実践編
実際に私がVuex→composables移行で3週間かかった作業を、この設計パターンなら1週間で完了できる理由を、ハマりやすい5つの落とし穴とその回避策と共に解説します。
この実装パターンを知らずに移行すると、状態の初期化エラーで2日、循環参照の解決で1日は確実にロスします。以下で解説する3層設計と具体的なコード例で、これらを事前回避できます。
実装の全体像
composablesによる状態管理は、大きく3つのレイヤーに分けて設計します。
最下層は「プリミティブな状態管理」を担うcomposables。「ref」や「reactive」を使った基本的な状態の読み書きのみを責務とします。中間層は「ビジネスロジック」を担うcomposables。APIとの通信、データの加工、バリデーションなどを担当し、下層のプリミティブな状態管理composableを組み合わせて使用します。上層は「UIロジック」を担うcomposables。コンポーネントが必要とする形に整えられた状態と操作を提供します。
// 下層:プリミティブな状態管理
const useUserState = () => {
const user = ref(null)
const isLoading = ref(false)
const setUser = (userData) => {
user.value = userData
}
return {
user: readonly(user),
isLoading: readonly(isLoading),
setUser
}
}
// 中間層:ビジネスロジック
const useAuth = () => {
const { user, setUser, isLoading } = useUserState()
const router = useRouter()
const login = async (credentials) => {
isLoading.value = true
try {
const userData = await authAPI.login(credentials)
setUser(userData)
await router.push('/dashboard')
} finally {
isLoading.value = false
}
}
return {
user,
isLoading,
login
}
}コード・設定例
グローバルな状態管理が必要なcomposablesは、Nuxt3のプラグインシステムを活用して初期化します。
// plugins/auth.client.js
export default defineNuxtPlugin(async () => {
const { initializeAuth } = useAuth()
await initializeAuth()
})
// composables/useAuth.js
export const useAuth = () => {
const user = useState('auth.user', () => null)
const isAuthenticated = computed(() => !!user.value)
const initializeAuth = async () => {
if (process.server) return
const token = localStorage.getItem('auth-token')
if (token) {
try {
const userData = await authAPI.verifyToken(token)
user.value = userData
} catch (error) {
localStorage.removeItem('auth-token')
}
}
}
const logout = async () => {
user.value = null
localStorage.removeItem('auth-token')
await navigateTo('/login')
}
return {
user: readonly(user),
isAuthenticated,
initializeAuth,
logout
}
}データフェッチングが必要なcomposablesでは、キャッシュとリフレッシュの仕組みを含めて設計します。
// composables/useApiCache.js
const useApiCache = () => {
const cache = useState('api.cache', () => new Map())
const getCached = (key) => {
const item = cache.value.get(key)
if (!item) return null
const now = Date.now()
if (now - item.timestamp > item.ttl) {
cache.value.delete(key)
return null
}
return item.data
}
const setCache = (key, data, ttl = 300000) => {
cache.value.set(key, {
data,
timestamp: Date.now(),
ttl
})
}
return { getCached, setCache }
}
// composables/useUserList.js
export const useUserList = () => {
const { getCached, setCache } = useApiCache()
const users = ref([])
const isLoading = ref(false)
const fetchUsers = async (force = false) => {
const cacheKey = 'users:list'
if (!force) {
const cached = getCached(cacheKey)
if (cached) {
users.value = cached
return
}
}
isLoading.value = true
try {
const data = await userAPI.getUsers()
users.value = data
setCache(cacheKey, data)
} finally {
isLoading.value = false
}
}
return {
users: readonly(users),
isLoading: readonly(isLoading),
fetchUsers
}
}ハマりやすいポイントと対処法
SSRとクライアントサイドでの状態の不一致が最も頻繁に発生する問題です。特にlocalStorageやsessionStorageに依存した状態管理を行っている場合、サーバーサイドでは値が取得できないため、ハイドレーション時に状態が変わってしまいます。
この問題は、サーバーサイドとクライアントサイドで異なる初期化処理を定義することで解決できます。
// composables/useClientOnlyState.js
export const useClientOnlyState = (key, defaultValue) => {
const state = useState(key, () => defaultValue)
onMounted(() => {
// クライアントサイドでのみ実行される初期化
const stored = localStorage.getItem(key)
if (stored) {
state.value = JSON.parse(stored)
}
})
watch(state, (newValue) => {
if (process.client) {
localStorage.setItem(key, JSON.stringify(newValue))
}
}, { deep: true })
return state
}composablesの循環参照も注意が必要です。複数のcomposablesが相互に依存する場合、意図しない循環参照が発生することがあります。これは依存関係を明確に定義し、必要に応じてイベントエミッターパターンを活用することで回避できます。
// utils/eventBus.js
import mitt from 'mitt'
export const eventBus = mitt()
// composables/useNotification.js
export const useNotification = () => {
const notifications = ref([])
onMounted(() => {
eventBus.on('notify', addNotification)
})
onUnmounted(() => {
eventBus.off('notify', addNotification)
})
const addNotification = (message) => {
notifications.value.push({
id: Date.now(),
message,
createdAt: new Date()
})
}
return {
notifications: readonly(notifications)
}
}
// 他のcomposablesから通知を送信
const notifyUser = (message) => {
eventBus.emit('notify', message)
}まとめ:次に何をすればいいか
Vuexからcomposablesへの移行は、単純な技術的変換ではなく、状態管理の設計思想を見直す機会として捉えることができます。まずは現在のVuexで管理している状態を分類し、本当にグローバル管理が必要な状態を特定することから始めてみてください。
移行は段階的に進めることをお勧めします。新機能はcomposablesで実装し、既存機能は必要に応じて移行していく。この方法により、リスクを最小限に抑えながら新しい設計パターンに慣れていくことができます。
実装時は、composablesの責務を明確に分離し、テスタビリティを保つことを意識してください。適切に設計されたcomposablesは、Vuexよりもシンプルで保守しやすい状態管理を実現できるはずです。
---
## さらに深く学びたい方へ
この記事が参考になったら「スキ」をお願いします。
### 関連する有料記事
**Claude Codeの実践的なノウハウ**
🔧 [Claude Code導入でハマった21の落とし穴](https://note.com/ai_dev_notes/n/n99ee547f40f1)
→ 導入時に誰もが踏む地雷とその回避法をすべて解説(¥1,480)
📚 [Claude Code Skills/Hooks完全カタログ](https://note.com/ai_dev_notes/n/nfe79dfbb8eeb)
→ コピペで使える実践テンプレート集(¥1,480)
🛠️ [Hooks/MCP完全トラブルシューティング](https://note.com/ai_dev_notes/n/n0327364955ec)
→ エラー別の解決法を網羅(¥1,480)
**エンジニア副業で稼ぐノウハウ**
💰 [副業時給¥3,000→¥8,000にした「3つの判断軸」](https://note.com/ai_dev_notes/n/na3eea4fb81e2)
→ 案件選び・断る技術・提案術の実践ノウハウ(¥980)
---
**フォローすると新着記事が届きます** → [@ai_dev_notes](https://note.com/ai_dev_notes)