State Management logo

State Management

Community
AsyrafHussin
state-management

React Query and Zustand patterns for state management. Use when implementing data fetching, caching, mutations, or client-side state. Triggers on tasks involving useQuery, useMutation, Zustand stores, caching, or state management.

Overview

PublisherAsyrafHussin
Repositoryagent-skills
Skill namestate-management
Stars
78
Forks
10
Bundled files
30
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 30 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by AsyrafHussin on GitHub. Read the source before you install it.

Installation

Install the State Management AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/AsyrafHussin/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/state-management .claude/skills/state-management
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable State Management in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads State Management on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so State Management is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

State Management with React Query + Zustand

Version 1.1.0 | TanStack Query v5 | Zustand v5 | March 2026

Note: This document provides comprehensive patterns for AI agents and LLMs working with TanStack Query v5 and Zustand v5. All examples are verified against v5 APIs. Optimized for automated refactoring, code generation, and state management best practices.

v5 Breaking Changes (Quick Reference)

TanStack Query v5:

  • cacheTimegcTime
  • keepPreviousData option → placeholderData: keepPreviousData (imported helper)
  • isPreviousDataisPlaceholderData
  • onSuccess/onError/onSettled removed from useQuery — still valid on useMutation
  • suspense: true on useQuery removed → use useSuspenseQuery

Zustand v5:

  • shallow as 2nd arg removed → useShallow from zustand/shallow
  • Selectors returning new references need useShallow to avoid infinite loops

Security: Persist Middleware

Never persist auth tokens, passwords, or secrets to localStorage/sessionStorage. Use partialize to persist only non-sensitive state. Manage tokens via HttpOnly cookies.


Comprehensive patterns for server state (React Query) and client state (Zustand). Contains 26+ rules for efficient data fetching and state management.

When to Apply

Reference these guidelines when:

  • Fetching data from APIs
  • Managing server state and caching
  • Handling mutations and optimistic updates
  • Creating client-side stores
  • Combining React Query with Zustand

Rule Categories by Priority

PriorityCategoryImpactPrefix
1React Query BasicsCRITICALrq-
2Zustand Store PatternsCRITICALzs-
3Caching & InvalidationHIGHcache-
4Mutations & UpdatesHIGHmut-
5Optimistic UpdatesMEDIUMopt-
6DevTools & DebuggingMEDIUMdev-
7Advanced PatternsLOWadv-

Quick Reference

1. React Query Basics (CRITICAL)

  • rq-setup - QueryClient and Provider setup
  • rq-usequery - Basic useQuery patterns
  • rq-querykeys - Query key organization
  • rq-loading-error - Handle loading and error states
  • rq-enabled - Conditional queries

2. Zustand Store Patterns (CRITICAL)

  • zs-create-store - Create basic store
  • zs-typescript - TypeScript store patterns
  • zs-selectors - Efficient selectors
  • zs-actions - Action patterns
  • zs-persist - Persist state to storage

3. Caching & Invalidation (HIGH)

  • cache-stale-time - Configure stale time
  • cache-gc-time - Configure garbage collection
  • cache-invalidation - Invalidate queries
  • cache-prefetch - Prefetch data
  • cache-initial-data - Set initial data

4. Mutations & Updates (HIGH)

  • mut-usemutation - Basic useMutation
  • mut-callbacks - onSuccess, onError callbacks
  • mut-invalidate - Invalidate after mutation
  • mut-update-cache - Direct cache updates

5. Optimistic Updates (MEDIUM)

  • opt-basic - Basic optimistic updates
  • opt-rollback - Rollback on error
  • opt-variables - Use mutation variables

6. DevTools & Debugging (MEDIUM)

  • dev-react-query - React Query DevTools
  • dev-zustand - Zustand DevTools
  • dev-debugging - Debug strategies

7. Advanced Patterns (LOW)

  • adv-infinite-queries - Infinite scrolling
  • adv-parallel-queries - Parallel requests
  • adv-dependent-queries - Dependent queries
  • adv-query-zustand - Combine RQ with Zustand

React Query Patterns

Setup

tsx
// lib/queryClient.ts
import { QueryClient } from '@tanstack/react-query'

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutes
      gcTime: 1000 * 60 * 30,   // 30 minutes (formerly cacheTime)
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
})

// App.tsx
import { QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { queryClient } from './lib/queryClient'

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Router />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  )
}

Query Keys Factory

tsx
// lib/queryKeys.ts
export const queryKeys = {
  // All posts
  posts: {
    all: ['posts'] as const,
    lists: () => [...queryKeys.posts.all, 'list'] as const,
    list: (filters: PostFilters) =>
      [...queryKeys.posts.lists(), filters] as const,
    details: () => [...queryKeys.posts.all, 'detail'] as const,
    detail: (id: number) => [...queryKeys.posts.details(), id] as const,
  },

  // All users
  users: {
    all: ['users'] as const,
    detail: (id: number) => [...queryKeys.users.all, id] as const,
    posts: (userId: number) => [...queryKeys.users.all, userId, 'posts'] as const,
  },
}

useQuery Hook

tsx
// hooks/usePosts.ts
import { useQuery } from '@tanstack/react-query'
import { queryKeys } from '@/lib/queryKeys'
import { fetchPosts, fetchPost } from '@/api/posts'

export function usePosts(filters?: PostFilters) {
  return useQuery({
    queryKey: queryKeys.posts.list(filters ?? {}),
    queryFn: () => fetchPosts(filters),
  })
}

export function usePost(id: number) {
  return useQuery({
    queryKey: queryKeys.posts.detail(id),
    queryFn: () => fetchPost(id),
    enabled: !!id, // Only run if id exists
  })
}

// Usage in component
function PostList() {
  const { data: posts, isLoading, error } = usePosts()

  if (isLoading) return <Spinner />
  if (error) return <Error message={error.message} />

  return (
    <ul>
      {posts?.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

useMutation Hook

tsx
// hooks/useCreatePost.ts
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { queryKeys } from '@/lib/queryKeys'
import { createPost } from '@/api/posts'

export function useCreatePost() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: createPost,
    onSuccess: (newPost) => {
      // Invalidate and refetch posts list
      queryClient.invalidateQueries({
        queryKey: queryKeys.posts.lists(),
      })
    },
    onError: (error) => {
      console.error('Failed to create post:', error)
    },
  })
}

// Usage
function CreatePostForm() {
  const { mutate, isPending } = useCreatePost()

  const handleSubmit = (data: CreatePostData) => {
    mutate(data)
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* form fields */}
      <button disabled={isPending}>
        {isPending ? 'Creating...' : 'Create'}
      </button>
    </form>
  )
}

Optimistic Updates

tsx
export function useUpdatePost() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: updatePost,
    onMutate: async (updatedPost) => {
      // Cancel outgoing refetches
      await queryClient.cancelQueries({
        queryKey: queryKeys.posts.detail(updatedPost.id),
      })

      // Snapshot previous value
      const previousPost = queryClient.getQueryData(
        queryKeys.posts.detail(updatedPost.id)
      )

      // Optimistically update
      queryClient.setQueryData(
        queryKeys.posts.detail(updatedPost.id),
        updatedPost
      )

      return { previousPost }
    },
    onError: (err, updatedPost, context) => {
      // Rollback on error
      queryClient.setQueryData(
        queryKeys.posts.detail(updatedPost.id),
        context?.previousPost
      )
    },
    onSettled: (data, error, variables) => {
      // Refetch after settle
      queryClient.invalidateQueries({
        queryKey: queryKeys.posts.detail(variables.id),
      })
    },
  })
}

Zustand Patterns

Basic Store

tsx
// stores/useCounterStore.ts
import { create } from 'zustand'

interface CounterState {
  count: number
  increment: () => void
  decrement: () => void
  reset: () => void
}

export const useCounterStore = create<CounterState>((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
  reset: () => set({ count: 0 }),
}))

// Usage
function Counter() {
  const { count, increment, decrement } = useCounterStore()

  return (
    <div>
      <span>{count}</span>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  )
}

Store with TypeScript and Middleware

tsx
// stores/useAuthStore.ts
import { create } from 'zustand'
import { persist, devtools } from 'zustand/middleware'

interface User {
  id: number
  name: string
  email: string
}

interface AuthState {
  user: User | null
  isAuthenticated: boolean
  login: (user: User) => void
  logout: () => void
}

// ✅ Never persist tokens to localStorage — use HttpOnly cookies server-side
export const useAuthStore = create<AuthState>()(
  devtools(
    persist(
      (set) => ({
        user: null,
        isAuthenticated: false,

        login: (user) =>
          set({
            user,
            isAuthenticated: true,
          }),

        logout: () =>
          set({
            user: null,
            isAuthenticated: false,
          }),
      }),
      {
        name: 'auth-storage',
        // Only persist display info and auth flag — tokens must NOT be included
        partialize: (state) => ({
          user: state.user,
          isAuthenticated: state.isAuthenticated,
        }),
      }
    )
  )
)

Selectors for Performance

tsx
// Use selectors to prevent unnecessary re-renders
function UserName() {
  // Only re-renders when user.name changes
  const name = useAuthStore((state) => state.user?.name)
  return <span>{name}</span>
}

// Multiple selectors
function UserInfo() {
  const user = useAuthStore((state) => state.user)
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)

  if (!isAuthenticated) return <LoginButton />
  return <span>{user?.name}</span>
}

Combining React Query + Zustand

tsx
// Server state: React Query (what comes from API)
const { data: posts } = usePosts()

// Client state: Zustand (UI state)
const { selectedPostId, selectPost } = useUIStore()

// Use together
const selectedPost = posts?.find((p) => p.id === selectedPostId)

How to Use

Read individual rule files for detailed explanations and code examples:

rules/rq-usequery.md
rules/rq-query-keys.md
rules/rq-mutation-setup.md
rules/rq-optimistic-updates.md
rules/zs-create-store.md
rules/zs-persist.md
rules/rq-query-invalidation.md
rules/rq-prefetching.md

References

React Query (TanStack Query)

  1. TanStack Query Documentation
  2. React Query Overview
  3. Queries Guide
  4. Mutations Guide
  5. Query Keys Guide
  6. Optimistic Updates
  7. Infinite Queries
  8. Paginated Queries
  9. React Query DevTools

Zustand

  1. Zustand Demo
  2. Zustand GitHub
  3. Getting Started
  4. TypeScript Guide
  5. Persisting Store Data
  6. Zustand Recipes

License

This skill is provided as-is for educational and development purposes. React Query is MIT licensed by TanStack. Zustand is MIT licensed by Poimandres (pmnd.rs).

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the State Management AI skill do?

React Query and Zustand patterns for state management. Use when implementing data fetching, caching, mutations, or client-side state. Triggers on tasks involving useQuery, useMutation, Zustand stores, caching, or state management.

Why use State Management on TypingMind?

Because you install it once and use it with any model. State Management is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install State Management in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/AsyrafHussin/agent-skills/tree/main/skills/state-management. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use State Management?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with State Management?

As many as you like. As long as a model supports skills, you can use State Management with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the State Management AI skill free?

Yes. It is published on GitHub by AsyrafHussin under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇