Skip to main content
rule CX Codex

rerender-lazy-state-init — Claude Code rule

The rerender-lazy-state-init rule recommends lazy useState initialization for costly starting values. It helps when a React component reads stored settings or builds a data structure.

MIT ★ 7,191 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/rerender-lazy-state-init.md
Open on GitHub

What rerender-lazy-state-init does

With useState(buildSearchIndex(items)), the function call is evaluated on each render, even though React uses that value only to initialize state. The rule shows the function form, useState(() => buildSearchIndex(items)), to defer the calculation. The same pattern applies when parsing settings from localStorage.

Use lazy initialization for values read from localStorage or sessionStorage, pulled from the DOM, or produced by heavy transformations. Simple values such as useState(0) do not need it. That distinction matters: a direct expensive call runs again on subsequent renders. For Claude Code, add .claude/rules/rerender-lazy-state-init.md to the project rules.

What it helps with

  • avoid rebuilding a search index on each render
  • defer parsing stored settings until state initialization
  • prevent a costly transformation from running after every component update

Example prompts for the agent

  • Check this component and move search-index construction into a lazy useState initializer.
  • Find expensive state initializers and switch direct calls to the function form.
  • Review whether settings from localStorage are being read on every render.

How to install rerender-lazy-state-init

Manually: put the files in place

.claude/rules/rerender-lazy-state-init.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 rerender-lazy-state-init

How do I install rerender-lazy-state-init in Claude Code?

Add the rule file at .claude/rules/rerender-lazy-state-init.md.

What does rerender-lazy-state-init do?

It recommends passing a function to useState when computing the initial value is expensive. React then uses that initializer for the initial render rather than evaluating the expression on every render.

Should I use lazy initialization for useState(0)?

No. The rule says the function form is unnecessary for simple primitives and cheap literals.

Source text

rerender-lazy-state-init.md · MIT
---
title: Use Lazy State Initialization
impact: MEDIUM
impactDescription: wasted computation on every render
tags: react, hooks, useState, performance, initialization
---

## Use Lazy State Initialization

Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.

**Incorrect (runs on every render):**

```tsx
function FilteredList({ items }: { items: Item[] }) {
  // buildSearchIndex() runs on EVERY render, even after initialization
  const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
  const [query, setQuery] = useState('')
  
  // When query changes, buildSearchIndex runs again unnecessarily
  return <SearchResults index={searchIndex} query={query} />
}

function UserProfile() {
  // JSON.parse runs on every render
  const [settings, setSettings] = useState(
    JSON.parse(localStorage.getItem('settings') || '{}')
  )
  
  return <SettingsForm settings={settings} onChange={setSettings} />
}
```

**Correct (runs only once):**

```tsx
function FilteredList({ items }: { items: Item[] }) {
  // buildSearchIndex() runs ONLY on initial render
  const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
  const [query, setQuery] = useState('')
  
  return <SearchResults index={searchIndex} query={query} />
}

function UserProfile() {
  // JSON.parse runs only on initial render
  const [settings, setSettings] = useState(() => {
    const stored = localStorage.getItem('settings')
    return stored ? JSON.parse(stored) : {}
  })
  
  return <SettingsForm settings={settings} onChange={setSettings} />
}
```

Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.

For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.

© tech-leads-club · MIT · tech-leads-club/agent-skills

Similar IDE rules

All IDE rules for Frontend and UI →

From the same set130

The whole set →
js-cache-function-results js-cache-function-results instructs the agent to cache repeated function calls using a module-level Map. It eliminates redundant computations across renders and utility calls. CX Codex +1 ★ 7,191repo stars client-localstorage-schema The client-localstorage-schema rule guides Claude Code to version localStorage keys and keep only fields the UI needs. Use it when changing client-side settings or cached user data. CX Codex +1 ★ 7,191repo stars client-event-listeners client-event-listeners — a Claude rule that keeps a single keydown listener on window no matter how many components call the shortcut hook. CX Codex +1 ★ 7,191repo stars server-after-nonblocking server-after-nonblocking instructs the agent to schedule logging, analytics, and cleanup with Next.js after(). This sends responses right away without waiting for background work. CX Codex +1 ★ 7,191repo stars async-defer-await async-defer-await — a rule that moves await operations into code branches where they're actually needed, preventing blockage of execution paths that may exit early. CX Codex +1 ★ 7,191repo stars server-dedup-props server-dedup-props — a rule for Claude Code about React Server Components: RSC-to-client serialization deduplicates by reference, not value. Server-side transforms like toSorted or filter create new references and double the payload. CX Codex +1 ★ 7,191repo stars rendering-usetransition-loading rendering-usetransition-loading — a rule that swaps hand-rolled loading flags in React components for useTransition. Useful when a spinner runs on its own useState. CX Codex +1 ★ 7,191repo stars server-cache-react server-cache-react instructs the assistant to deduplicate server-side operations with React.cache() and prevent cache misses from inline object arguments. CX Codex +1 ★ 7,191repo stars

Project sponsors

Companies that keep this analytics open