Using a Store Outside of a Component

Pinia-React stores can be used inside and outside of React components. While the generated useAuthStore() hook is designed for components, you can use the generated getAuthStore() function for all other scenarios. The generic useStore() and getStore() helpers remain available for backwards compatibility.

The getAuthStore function

When you define a store with defineStore('auth', ...), it generates useAuthStore (the hook) and getAuthStore (a plain function) from the store ID.

The recommended pattern is to export both generated functions from your store definition file. The generic useStore and getStore helpers are also available.

src/stores/auth-store.ts
import { defineStore } from 'pinia-react'

const { useAuthStore, getAuthStore } = defineStore('auth', {
  state: () => ({
    isAuthenticated: false,
    // ...
  }),
  actions: {
    logout() {
      this.isAuthenticated = false
    }
  }
})

Example Usage

Now, you can import getAuthStore in any JavaScript module, like a service file, an API client, or another store's action.

Here is an example of calling a store's action from a utility function:

src/auth-service.ts
import { getAuthStore } from './stores/auth-store'

export function performLogout() {
  // Get the store instance by calling getAuthStore()
  const authStore = getAuthStore()

  // You can now access state, getters, or actions
  if (authStore.isAuthenticated) {
    authStore.logout()
    console.log('User has been logged out.')
  }
}

This pattern ensures that you are always accessing the same, single instance of the store throughout your application, whether you are in a component or not.