Defining a Store

A Store is defined using defineStore(). Its first parameter is a unique ID that Pinia uses to identify the store.

Store IDs must be unique within a Pinia instance. Duplicate definitions warn in development; use a distinct ID for each Store.

import { defineStore } from 'pinia-react'

// `defineStore()` generates named helpers from the store ID.
// For `alerts`, the generated helpers are `useAlertsStore` and `getAlertsStore`.
const { useAlertsStore, getAlertsStore } = defineStore('alerts', {
  // Other configurations...
})

It's recommended to name the exported hook starting with use and ending with Store (e.g., useUserStore, useCartStore). This follows standard React Hook conventions.

Option Store

You define a store's configuration by passing an options object with state, getters, and actions properties.

export const { useCounterStore, getCounterStore } = defineStore('counter', {
  state: () => ({ count: 0, name: 'Eduardo' }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

Using the Store

After defining the store, simply import and call its hook in your component.

import React from 'react';
import { useCounterStore } from './counterStore';

export function App() {
  const counter = useCounterStore();

  return (
    <div>
      <h2>Pinia-React Count: {counter.count}</h2>
    </div>
  );
}

Provider and external access

Component Hooks use the nearest PiniaProvider, then active Pinia. Plain accessors do not read React Context; pass getCounterStore(pinia) in multi-instance services. See Stores outside components for instance lifetime and Next.js for request snapshots. The simple single-root setup does not need a Provider.