Advanced State Management in React: Exploring Recoil and Jotai

A deep dive into modern state management libraries like Recoil and Jotai as alternatives to Redux.

0 likes
11 views

Rule Content

{
  "title": "Advanced State Management in React: Exploring Recoil and Jotai",
  "description": "A deep dive into modern state management libraries like Recoil and Jotai as alternatives to Redux.",
  "category": "React Cursor Rules",
  "rules": [
    {
      "name": "Organize Atoms by Functionality",
      "description": "Group Recoil atoms into separate files based on their functionality to improve code organization and maintainability.",
      "version": "1.0.0",
      "author": "Your Name",
      "date": "2025-06-03",
      "globs": [
        "**/*.js",
        "**/*.jsx",
        "**/*.ts",
        "**/*.tsx"
      ],
      "tags": [
        "recoil",
        "state-management",
        "organization"
      ],
      "examples": [
        {
          "before": "// userState.js\nimport { atom } from 'recoil';\nexport const userState = atom({\n  key: 'userState',\n  default: { name: '', age: 0 },\n});",
          "after": "// userState.js\nimport { atom } from 'recoil';\nexport const userState = atom({\n  key: 'userState',\n  default: { name: '', age: 0 },\n});"
        }
      ]
    },
    {
      "name": "Leverage Selectors for Derived State",
      "description": "Use Recoil selectors to compute derived state efficiently, reducing redundancy and improving performance.",
      "version": "1.0.0",
      "author": "Your Name",
      "date": "2025-06-03",
      "globs": [
        "**/*.js",
        "**/*.jsx",
        "**/*.ts",
        "**/*.tsx"
      ],
      "tags": [
        "recoil",
        "selectors",
        "derived-state"
      ],
      "examples": [
        {
          "before": "import { selector } from 'recoil';\nimport { cartState } from './cartState';\nexport const totalCartItems = selector({\n  key: 'totalCartItems',\n  get: ({ get }) => {\n    const cart = get(cartState);\n    return cart.length;\n  },\n});",
          "after": "import { selector } from 'recoil';\nimport { cartState } from './cartState';\nexport const totalCartItems = selector({\n  key: 'totalCartItems',\n  get: ({ get }) => {\n    const cart = get(cartState);\n    return cart.length;\n  },\n});"
        }
      ]
    },
    {
      "name": "Use Asynchronous Selectors for API Calls",
      "description": "Handle asynchronous operations in Recoil by using async selectors to manage API requests and loading states.",
      "version": "1.0.0",
      "author": "Your Name",
      "date": "2025-06-03",
      "globs": [
        "**/*.js",
        "**/*.jsx",
        "**/*.ts",
        "**/*.tsx"
      ],
      "tags": [
        "recoil",
        "async",
        "selectors"
      ],
      "examples": [
        {
          "before": "export const userData = selector({\n  key: 'userData',\n  get: async () => {\n    const response = await fetch('/api/user');\n    if (!response.ok) throw new Error('Failed to fetch user data');\n    return response.json();\n  },\n});",
          "after": "export const userData = selector({\n  key: 'userData',\n  get: async () => {\n    const response = await fetch('/api/user');\n    if (!response.ok) throw new Error('Failed to fetch user data');\n    return response.json();\n  },\n});"
        }
      ]
    },
    {
      "name": "Minimize Atom Usage for Performance",
      "description": "Avoid overusing Recoil atoms to prevent performance issues; group related state into single atoms when appropriate.",
      "version": "1.0.0",
      "author": "Your Name",
      "date": "2025-06-03",
      "globs": [
        "**/*.js",
        "**/*.jsx",
        "**/*.ts",
        "**/*.tsx"
      ],
      "tags": [
        "recoil",
        "performance",
        "atoms"
      ],
      "examples": [
        {
          "before": "const userAtom = atom({ name: '', age: 0 });",
          "after": "const userAtom = atom({ name: '', age: 0 });"
        }
      ]
    },
    {
      "name": "Persist State with Recoil’s Persistence Layer",
      "description": "Use Recoil's persistence features to maintain state across page reloads, enhancing user experience.",
      "version": "1.0.0",
      "author": "Your Name",
      "date": "2025-06-03",
      "globs": [
        "**/*.js",
        "**/*.jsx",
        "**/*.ts",
        "**/*.tsx"
      ],
      "tags": [
        "recoil",
        "persistence",
        "state-management"
      ],
      "examples": [
        {
          "before": "import { atom } from 'recoil';\nexport const userState = atom({\n  key: 'userState',\n  default: { name: '', loggedIn: false },\n  effects_UNSTABLE: [\n    ({ setSelf, onSet }) => {\n      const savedUser = localStorage.getItem('userState');\n      if (savedUser) setSelf(JSON.parse(savedUser));\n      onSet((newUser) => {\n        localStorage.setItem('userState', JSON.stringify(newUser));\n      });\n    },\n  ],\n});",
          "after": "import { atom } from 'recoil';\nexport const userState = atom({\n  key: 'userState',\n  default: { name: '', loggedIn: false },\n  effects_UNSTABLE: [\n    ({ setSelf, onSet }) => {\n      const savedUser = localStorage.getItem('userState');\n      if (savedUser) setSelf(JSON.parse(savedUser));\n      onSet((newUser) => {\n        localStorage.setItem('userState', JSON.stringify(newUser));\n      });\n    },\n  ],\n});"
        }
      ]
    },
    {
      "name": "Use Jotai's Write-Only Atoms for Side Effects",
      "description": "Implement write-only atoms in Jotai to handle side effects and separate mutations from components.",
      "version": "1.0.0",
      "author": "Your Name",
      "date": "2025-06-03",
      "globs": [
        "**/*.js",
        "**/*.jsx",
        "**/*.ts",
        "**/*.tsx"
      ],
      "tags": [
        "jotai",
        "side-effects",
        "write-only-atoms"
      ],
      "examples": [
        {
          "before": "const countAtom = atom(0);\nconst incrementCountAtom = atom(null, async (get, set, arg) => {\n  await wait(500);\n  set(countAtom, p => p + 1);\n});\nfunction App() {\n  const count = useAtomValue(countAtom);\n  const incrementCount = useSetAtom(incrementCountAtom);\n  return <button onClick={incrementCount}>{count}</button>\n}",
          "after": "const countAtom = atom(0);\nconst incrementCountAtom = atom(null, async (get, set, arg) => {\n  await wait(500);\n  set(countAtom, p => p + 1);\n});\nfunction App() {\n  const count = useAtomValue(countAtom);\n  const incrementCount = useSetAtom(incrementCountAtom);\n  return <button onClick={incrementCount}>{count}</button>\n}"
        }
      ]
    },
    {
      "name": "Group Related State into Single Jotai Atoms",
      "description": "Combine related pieces of state into a single Jotai atom to reduce complexity and improve maintainability.",
      "version": "1.0.0",
      "author": "Your Name",
      "date": "2025-06-03",
      "globs": [
        "**/*.js",
        "**/*.jsx",
        "**/*.ts",
        "**/*.tsx"
      ],
      "tags": [
        "jotai",
        "state-management",
        "organization"
      ],
      "examples": [
        {
          "before": "const userAtom = atom({ name: '', age: 0 });\nconst UserProfile = () => {\n  const [user, setUser] = useAtom(userAtom);\n  const updateProfile = (name, age) => {\n    setUser({ ...user, name, age });\n  };\n  return (\n    <div>\n      <p>Name: {user.name}</p>\n      <p>Age: {user.age}</p>\n      {/* Update profile logic */}\n    </div>\n  );\n};",
          "after": "const userAtom = atom({ name: '', age: 0 });\nconst UserProfile = () => {\n  const [user, setUser] = useAtom(userAtom);\n  const updateProfile = (name, age) => {\n    setUser({ ...user, name, age });\n  };\n  return (\n    <div>\n      <p>Name: {user.name}</p>\n      <p>Age: {user.age}</p>\n      {/* Update profile logic */}\n    </div>\n  );\n};"
        }
      ]
    },
    {
      "name": "Leverage Jotai's Computed Atoms for Derived State",
      "description": "Use Jotai's computed atoms to create derived state, reducing redundancy and improving performance.",
      "version": "1.0.0",
      "author": "Your Name",
      "date": "2025-06-03",
      "globs": [
        "**/*.js",
        "**/*.jsx",
        "**/*.ts",
        "**/*.tsx"
      ],
      "tags": [
        "jotai",
        "computed-atoms",
        "