Using a Store Outside of a Component

Pinia-React stores can be used inside and outside of React components. While useStore() is a hook designed for components, you can use the getStore() function for all other scenarios.

The getStore function

When you define a store, defineStore() returns an object containing both useStore (the hook) and getStore (a plain function).

The recommended pattern is to export both from your store definition file.

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

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

export const useAuthStore = useStore
export const getAuthStore = getStore

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 getStore()
  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.