agentleFS
Piyush8296Piyush8296/claude-workspace/.claude/skills/state-management/SKILL.md

state-management

Skill2 starsChanged 7 months agoMITView on GitHub

State management strategies for React — local state, server state, global state, URL state. Use when deciding state architecture, implementing data fetching, or managing complex state.

18 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use testing and api-design.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • NVIDIASkill

    testing

    Run Python and Rust tests for physicsnemo-curator using uv + pytest with coverage reporting via pytest-cov, and cargo-nextest for Rust tests. Includes benchmark workflows with pytest-benchmark and criterion.

    Also in 4 projects that use this

  • MicrosoftSkill

    api-design

    Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 1 is distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 15 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Before choosing a tool, classify the state:

    line 10
  2. Very specific:

    Golden rule: Use the simplest tool that fits.

    line 21

“Common” is measured: kept by at least 6 in 10 of the 15 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

State Management

The State Classification Framework

Before choosing a tool, classify the state:

TypeScopeToolExample
UI StateSingle componentuseStateModal open, input value
Shared UI StateFew componentsLift state + props / ContextActive tab, sidebar collapsed
Server StateCached remote dataTanStack Query / SWRUser list, profile data
Global App StateEntire appZustand / JotaiAuth, theme, feature flags
URL StateNavigationuseSearchParams / routerFilters, pagination, sort
Form StateForm lifecycleReact Hook Form / FormikInput values, validation

Golden rule: Use the simplest tool that fits. useState > Context > Zustand > Redux.

Server State (TanStack Query)

This is the most common state type in frontend apps. Most "global state" is actually server state.

Query Pattern

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

// Query keys as const for type safety
export const userKeys = {
  all: ['users'] as const,
  lists: () => [...userKeys.all, 'list'] as const,
  list: (filters: UserFilters) => [...userKeys.lists(), filters] as const,
  details: () => [...userKeys.all, 'detail'] as const,
  detail: (id: string) => [...userKeys.details(), id] as const,
};

// Query hook
export function useUsers(filters: UserFilters) {
  return useQuery({
    queryKey: userKeys.list(filters),
    queryFn: () => api.users.list(filters),
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

// Mutation hook with cache invalidation
export function useCreateUser() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: api.users.create,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: userKeys.lists() });
      toast.success('User created');
    },
    onError: (error) => {
      console.error('createUser failed:', error);
      toast.error('Failed to create user');
    },
  });
}

Optimistic Updates

export function useToggleFavorite() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: api.favorites.toggle,
    onMutate: async (itemId) => {
      // Cancel outgoing queries
      await queryClient.cancelQueries({ queryKey: ['items', itemId] });

      // Snapshot previous value
      const previous = queryClient.getQueryData(['items', itemId]);

      // Optimistically update
      queryClient.setQueryData(['items', itemId], (old: Item) => ({
        ...old,
        isFavorite: !old.isFavorite,
      }));

      return { previous };
    },
    onError: (_err, itemId, context) => {
      // Rollback on error
      queryClient.setQueryData(['items', itemId], context?.previous);
      toast.error('Failed to update');
    },
    onSettled: (_data, _err, itemId) => {
      // Refetch to ensure consistency
      queryClient.invalidateQueries({ queryKey: ['items', itemId] });
    },
  });
}

Global App State (Zustand)

import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

interface AuthStore {
  user: User | null;
  token: string | null;
  login: (credentials: Credentials) => Promise<void>;
  logout: () => void;
  isAuthenticated: () => boolean;
}

export const useAuthStore = create<AuthStore>()(
  devtools(
    persist(
      (set, get) => ({
        user: null,
        token: null,
        login: async (credentials) => {
          const { user, token } = await api.auth.login(credentials);
          set({ user, token }, false, 'auth/login');
        },
        logout: () => {
          set({ user: null, token: null }, false, 'auth/logout');
        },
        isAuthenticated: () => get().token !== null,
      }),
      { name: 'auth-storage' }
    ),
    { name: 'AuthStore' }
  )
);

Zustand best practices:

  • One store per domain (auth, theme, layout) — not one mega-store
  • Selectors to prevent unnecessary re-renders: useAuthStore((s) => s.user)
  • Actions inside the store, not in components
  • devtools middleware in development for debugging

URL State

import { useSearchParams } from 'react-router-dom'; // or next/navigation

function useFilters() {
  const [searchParams, setSearchParams] = useSearchParams();

  const filters = {
    query: searchParams.get('q') ?? '',
    page: Number(searchParams.get('page') ?? '1'),
    sort: (searchParams.get('sort') ?? 'newest') as SortOption,
  };

  const setFilter = (key: string, value: string) => {
    setSearchParams((prev) => {
      const next = new URLSearchParams(prev);
      if (value) {
        next.set(key, value);
      } else {
        next.delete(key);
      }
      // Reset page when filters change
      if (key !== 'page') next.set('page', '1');
      return next;
    });
  };

  return { filters, setFilter };
}

When to use URL state: Filters, pagination, sort order, selected tabs, modal open state — anything the user might want to share via link or use browser back/forward.

Decision Framework

Is it from an API?
  → Yes: TanStack Query (server state)
  → No: Continue

Should it survive page refresh?
  → Yes, in URL: useSearchParams (URL state)
  → Yes, persisted: Zustand with persist (global state)
  → No: Continue

Used by many unrelated components?
  → Yes: Zustand store (global state)
  → No: Continue

Used by parent + 1-2 children?
  → Yes: Lift state to parent (local/shared state)
  → No: useState in the component (local state)

Anti-Patterns

BadGoodWhy
useEffect to sync stateDerive from sourceExtra render cycle, bug-prone
Global store for form valuesReact Hook Form / local stateForms are local by nature
Context for frequently updating valuesZustand with selectorsContext re-renders all consumers
Fetching in useEffectTanStack QueryNo caching, no loading/error states, race conditions
Prop drilling 4+ levelsZustand or ContextMaintenance burden

Integration with Other Skills

  • react-patterns: Component state handling order
  • testing-strategy: Mocking stores and query clients in tests
  • performance-optimization: Selector optimization, re-render prevention

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.