Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build performant React Native and Expo apps with best practices for lists, animations, and navigation
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/react-state-minimize.md
1---2title: Minimize State Variables and Derive Values3impact: MEDIUM4impactDescription: fewer re-renders, less state drift5tags: state, derived-state, hooks, optimization6---78## Minimize State Variables and Derive Values910Use the fewest state variables possible. If a value can be computed from existing state or props, derive it during render instead of storing it in state. Redundant state causes unnecessary re-renders and can drift out of sync.1112**Incorrect (redundant state):**1314```tsx15function Cart({ items }: { items: Item[] }) {16const [total, setTotal] = useState(0)17const [itemCount, setItemCount] = useState(0)1819useEffect(() => {20setTotal(items.reduce((sum, item) => sum + item.price, 0))21setItemCount(items.length)22}, [items])2324return (25<View>26<Text>{itemCount} items</Text>27<Text>Total: ${total}</Text>28</View>29)30}31```3233**Correct (derived values):**3435```tsx36function Cart({ items }: { items: Item[] }) {37const total = items.reduce((sum, item) => sum + item.price, 0)38const itemCount = items.length3940return (41<View>42<Text>{itemCount} items</Text>43<Text>Total: ${total}</Text>44</View>45)46}47```4849**Another example:**5051```tsx52// Incorrect: storing both firstName, lastName, AND fullName53const [firstName, setFirstName] = useState('')54const [lastName, setLastName] = useState('')55const [fullName, setFullName] = useState('')5657// Correct: derive fullName58const [firstName, setFirstName] = useState('')59const [lastName, setLastName] = useState('')60const fullName = `${firstName} ${lastName}`61```6263State should be the minimal source of truth. Everything else is derived.6465Reference: [Choosing the State Structure](https://react.dev/learn/choosing-the-state-structure)66