Skip to main content
rule CX Codex

perf-zustand-selectors — Claude Code rule: Zustand selectors

perf-zustand-selectors — a rule file that pushes the agent to subscribe components to individual Zustand slices instead of the whole store, so a component repaints only when the data it reads changes.

MIT ★ 4,719 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/perf-zustand-selectors.md
Open on GitHub

What perf-zustand-selectors does

The rule gives the agent one habit: pull a single slice out of a Zustand store rather than the store object itself. Two examples sit in the file. One component reads the entire store and repaints whenever score or health moves; the other asks for playerX only.

Harder cases follow. Several values at once go through shallow imported from zustand/shallow. For values that change every frame there is useGameStore.subscribe(), which keeps the component from repainting, and animation code calls getState() inside useFrame. The file closes with a comparison table and a store layout that keeps actions and derived getters apart from state.

That table marks a bare useStore() call as “Never use”, so a component still wired that way is exactly what the rule flags. For Claude the file sits at .claude/rules/perf-zustand-selectors.md; nothing goes through a package manager.

What it helps with

  • stop a component from repainting on store updates it never reads
  • subscribe to several values at once with shallow
  • move a mesh every frame without React re-renders
  • keep actions and derived getters out of component subscriptions

Example prompts for the agent

  • This component only needs playerX — switch it to a Zustand selector.
  • The component repaints on every score change; move it onto a selector.
  • Update the position through useGameStore.subscribe() so the frame loop does not repaint.

How to install perf-zustand-selectors

Manually: put the files in place

.claude/rules/perf-zustand-selectors.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about perf-zustand-selectors

How do I install perf-zustand-selectors in Claude Code?

Put the rule text in .claude/rules/perf-zustand-selectors.md inside your project.

What does perf-zustand-selectors do?

It tells the agent how to rewrite Zustand subscriptions as selectors, so a component stops repainting on changes it does not use.

What goes wrong when a component calls the store without a selector?

It repaints on any store change, score and health included. The comparison table in the rule marks that call as “Never use”.

Source text

perf-zustand-selectors.md · MIT
# perf-zustand-selectors

**Use Zustand selectors to minimize re-renders.**

## Why It Matters

Subscribing to the entire Zustand store means your component re-renders whenever ANY value changes. Selectors let you subscribe to specific slices, so components only re-render when their specific data changes.

## Bad Example

```jsx
// BAD - Re-renders on ANY store change
function BadComponent() {
  const store = useGameStore(); // Subscribes to entire store
  return <mesh position-x={store.playerX} />;
}
```

If `score`, `health`, or any other value changes, this component re-renders even though it only uses `playerX`.

## Good Example

```jsx
// GOOD - Re-renders only when playerX changes
function GoodComponent() {
  const playerX = useGameStore(state => state.playerX);
  return <mesh position-x={playerX} />;
}
```

## Multiple Values with Shallow

```jsx
import { shallow } from 'zustand/shallow';

// GOOD - Re-renders only when x, y, or z changes
function PositionComponent() {
  const { x, y, z } = useGameStore(
    state => ({ x: state.x, y: state.y, z: state.z }),
    shallow // Use shallow comparison for objects
  );
  return <mesh position={[x, y, z]} />;
}
```

## Transient Subscriptions (No Re-renders)

For values that change every frame (like positions), use transient subscriptions:

```jsx
function TransientComponent() {
  const meshRef = useRef();

  useEffect(() => {
    // Subscribe without causing re-renders
    const unsubscribe = useGameStore.subscribe(
      state => state.playerPosition,
      position => {
        meshRef.current.position.copy(position);
      }
    );
    return unsubscribe;
  }, []);

  return <mesh ref={meshRef} />;
}
```

## getState() in useFrame

For animation, use `getState()` which doesn't subscribe:

```jsx
function AnimatedComponent() {
  const meshRef = useRef();

  useFrame(() => {
    // No subscription, no re-renders
    const { targetPosition, speed } = useStore.getState();
    meshRef.current.position.lerp(targetPosition, speed);
  });

  return <mesh ref={meshRef} />;
}
```

## Store Design for Performance

```jsx
const useGameStore = create((set, get) => ({
  // State
  playerX: 0,
  playerY: 0,
  score: 0,
  health: 100,

  // Actions (don't subscribe to these)
  movePlayer: (dx, dy) => set(state => ({
    playerX: state.playerX + dx,
    playerY: state.playerY + dy
  })),

  // Derived values as getters
  getPlayerPosition: () => {
    const { playerX, playerY } = get();
    return new THREE.Vector3(playerX, playerY, 0);
  }
}));
```

## Comparison

| Method | Re-renders | Use Case |
|--------|------------|----------|
| `useStore()` | Every change | Never use |
| `useStore(s => s.value)` | When value changes | Most cases |
| `useStore(selector, shallow)` | When any selected value changes | Multiple values |
| `useStore.subscribe()` | Never | Continuous updates |
| `useStore.getState()` | Never | Inside useFrame |

## References

- [Zustand Documentation](https://github.com/pmndrs/zustand)
- [R3F State Management](https://docs.pmnd.rs/react-three-fiber/tutorials/using-with-zustand)

© zebbern · MIT · zebbern/claude-code-guide

Similar IDE rules

All IDE rules for Frontend and UI →
zustand-store-ts Microsoft zustand-store-ts — a skill for Claude Code and GitHub Copilot that scaffolds Zustand stores with subscribeWithSelector and typed state/action separation. Drop it in when a React project needs global state with fine-grained subscriptions. CX Codex +1 3installs zustand vercel-labs This skill integrates Zustand into json-render to sync application state. Use it when your project already relies on Zustand and you need to connect it with components rendered by json-render. CX Codex +1 1,900installs zustand-patterns OrchestKit zustand-patterns — a skill for Claude Code enforces TypeScript-first patterns for Zustand 5.x state management. Triggers during store creation, slice composition, and middleware setup. CX Codex +1 1,500installs zustand-state-management Mindrally zustand-state-management enforces Zustand store best practices in React and TypeScript apps, covering store slices, SSR, and testing. It helps eliminate selector re-renders and hydration bugs. CX Codex +1 1,000installs zustand-5 prowler-cloud Zustand 5 state management patterns for Claude Code: basic stores, selectors, persist middleware, and slice composition. Prevents unnecessary re-renders and keeps state logic clean. CX Codex +1 912installs zustand-state-builder patricio0312rev zustand-state-builder — a skill for managing app state with Zustand: minimal API, full TypeScript support, persistence, and devtools. Runs on Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, and OpenCode. CX Codex +1 264installs

From the same set86

The whole set →
draw-call-optimization The draw-call-optimization rule for Claude Code guides Three.js optimization, reducing draw calls to below 100 per frame through instancing, batching, and geometry merging. CX Codex +1 ★ 4,719repo stars object-pooling object-pooling — a rule that pushes the agent to reuse bullets, particles and NPCs from a pool instead of building and discarding meshes every frame. CX Codex +1 ★ 4,719repo stars shader-mobile The shader-mobile rule for Claude Code provides guidelines for optimizing GLSL and Three.js shaders for mobile GPUs to prevent framerate drops on mobile devices. CX Codex +1 ★ 4,719repo stars drei-use-gltf The drei-use-gltf rule guides GLTF loading through useGLTF, including caching and preloading. It fits React Three Fiber scenes that need model assets. CX Codex +1 ★ 4,719repo stars geometry-instanced-mesh geometry-instanced-mesh guides AI agents to use THREE.InstancedMesh instead of separate meshes for repeating 3D objects. CX Codex +1 ★ 4,719repo stars webgpu-renderer The webgpu-renderer rule guides Three.js WebGPU setup with a WebGL 2 fallback. Use it when a 3D scene needs compute work, GPU particles, or indirect rendering. CX Codex +1 ★ 4,719repo stars tsl-material-slots tsl-material-slots is a Claude Code rule with a reference to Three.js TSL material slots. It helps write node-based shader logic without mistyping slot names or property types. CX Codex +1 ★ 4,719repo stars core-web-vitals core-web-vitals is a Claude Code rule for loading Three.js models and textures without letting heavy 3D delay first paint or degrade LCP, FID and CLS. CX Codex +1 ★ 4,719repo stars

Project sponsors

Companies that keep this analytics open