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. Defining the same ID twice warns in development, and the newer definition replaces the previous 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>
  );
}