Managing State with Provide and Inject for Deeply Nested Components

Understand how to use the provide/inject pattern for efficient state management in applications with deeply nested components.

0 likes
39 views

Rule Content

{
  "title": "Managing State with Provide and Inject for Deeply Nested Components",
  "description": "Ensure efficient state management in applications with deeply nested components by enforcing the use of the provide/inject pattern.",
  "category": "Vue Cursor Rules",
  "rule": {
    "name": "enforce-provide-inject-for-deeply-nested-components",
    "description": "Enforce the use of Vue's provide/inject pattern to manage state in deeply nested components, preventing prop drilling and maintaining clean component hierarchies.",
    "severity": "error",
    "options": [
      {
        "name": "maxPropDrillingDepth",
        "description": "The maximum depth of prop drilling allowed before requiring the use of provide/inject.",
        "type": "integer",
        "default": 2
      }
    ],
    "apply": "function (context) {\n  return {\n    'VElement[name=/^V[A-Z]/]': function (node) {\n      const propDrillingDepth = calculatePropDrillingDepth(node);\n      if (propDrillingDepth > context.options.maxPropDrillingDepth) {\n        context.report({\n          node,\n          message: `Prop drilling depth of ${propDrillingDepth} exceeds the allowed maximum of ${context.options.maxPropDrillingDepth}. Consider using provide/inject for state management.`\n        });\n      }\n    }\n  };\n}\n\nfunction calculatePropDrillingDepth(node) {\n  let depth = 0;\n  let current = node;\n  while (current.parent && current.parent.type === 'VElement') {\n    if (current.parent.attributes.some(attr => attr.key.name === 'props')) {\n      depth++;\n    }\n    current = current.parent;\n  }\n  return depth;\n}"
  }
}