Agent skill

Component Refactoring

by langflow-ai in langflow-ai/langflow

Refactor high-complexity React components in Langflow frontend.

MITAuto-check passedDevelopment

Install Component Refactoring

skills CLI
$ npx skills add langflow-ai/langflow --skill component-refactoring -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install langflow-ai/langflow component-refactoring --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/langflow-ai/langflow.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/component-refactoring .claude/skills/component-refactoring && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
component-refactoring
GitHub stars
156k
Token cost
~3.5k tokens
SKILL.md length
791 words
Files
4 (incl. references)
Skills in repo
10
Repo updated
First seen
Licence
MIT

At a glance

Refactor high-complexity React components in Langflow frontend.

  • Works in 8 steps: Zustand Store Selectors → Custom Node Components → Flow Canvas Components → …
  • Manual complexity assessment shows complexity 50
  • SKILL.md covers Quick Reference, Core Refactoring Patterns, Langflow-Specific Refactoring… and Refactoring Workflow, plus 2 more sections
  • Calls npm

What it does

Component Refactoring is an agent skill from langflow-ai/langflow. Refactor high-complexity React components in Langflow frontend. Use when manual complexity assessment shows complexity 50 or lineCount 300, when the user asks for code splitting, hook extraction, or complexity reduction; avoid for simple/well-structured components, third-party wrappers, or when the user explicitly wants testing without refactoring.

Its SKILL.md is about 3.5k tokens, which your agent loads only when the skill is triggered. The skill folder holds 4 other files, including reference files (for example `references/complexity-patterns.md`, `references/component-splitting.md` and `references/hook-extraction.md`).

It sits in Development, covering Refactoring and React components. The repository describes itself as: Langflow is a powerful tool for building and deploying AI-powered agents and workflows. The licence is MIT.

When your agent uses it

  • Manual complexity assessment shows complexity 50
  • The user asks for code splitting
  • Hook extraction
  • Complexity reduction

Example prompts

  • “/component-refactoring”

Workflow steps

8 steps, taken from the step headings in SKILL.md.

  1. Zustand Store Selectors
  2. Custom Node Components
  3. Flow Canvas Components
  4. API Query Hook Components
  5. Assess Complexity
  6. Plan
  7. Execute Incrementally
  8. Verify

What it can do on your machine

Read from SKILL.md and the folder at commit 504c02f. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • npm

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md. Its commands use npm, which can reach the network depending on how they are called.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Component Refactoring loads about 3.5k tokens when it runs, and up to ~14k if it reads all its reference files. Until then it costs about 94 tokens; SKILL.md has 791 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~94
When it runs · the whole SKILL.md, loaded when a task matches
~3.5k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~14k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from langflow-ai/langflow at commit 504c02f, republished under its MIT licence (© langflow-ai). 791 words, ~3,529 tokens.

Download SKILL.mdSave it as .claude/skills/component-refactoring/SKILL.md (or your agent's skills folder). This skill also uses 3 other files; get the full folder from GitHub.
name
component-refactoring
description
Refactor high-complexity React components in Langflow frontend. Use when manual complexity assessment shows complexity > 50 or lineCount > 300, when the user asks for code splitting, hook extraction, or complexity reduction; avoid for simple/well-structured components, third-party wrappers, or when the user explicitly wants testing without refactoring.

Langflow Component Refactoring Skill

Refactor high-complexity React components in the Langflow frontend codebase with the patterns and workflow below.

Complexity Threshold: Components with complexity > 50 (measured manually by counting conditionals, nesting levels, and lines) should be refactored before testing.

Quick Reference

Commands (run from src/frontend/)
bash
cd src/frontend

# Lint with Biome
npm run lint

# Type checking
npm run type-check

# Run tests
npm test
Manual Complexity Assessment

Since Langflow does not have automated complexity analysis tools, assess components manually:

  1. Count conditionals: Each if/else, switch/case, ternary, &&/|| chain adds +1.
  2. Count nesting levels: Each level of nesting within conditionals or loops adds +1.
  3. Count total lines: Target < 300 lines per component file.
  4. Count state hooks: More than 5 useState calls suggests hook extraction.
  5. Count effects: More than 3 useEffect calls suggests effect consolidation.
Complexity Score Interpretation
ScoreLevelAction
0-25SimpleReady for testing
26-50MediumConsider minor refactoring
51-75ComplexRefactor before testing
76-100Very ComplexMust refactor

Core Refactoring Patterns

Pattern 1: Extract Custom Hooks

When: Component has complex state management, multiple useState/useEffect, or business logic mixed with UI.

Langflow Convention: Place hooks in a hooks/ subdirectory or alongside the component as use-<feature>.ts. Langflow uses kebab-case filenames with use- prefix.

typescript
// Before: Complex state logic in component
const FlowPage: FC = () => {
  const [nodes, setNodes] = useState<Node[]>([])
  const [edges, setEdges] = useState<Edge[]>([])
  const [buildStatus, setBuildStatus] = useState<BuildStatus>(BuildStatus.IDLE)

  // 50+ lines of state management logic...

  return <div>...</div>
}

// After: Extract to custom hook
// hooks/use-flow-state.ts
export const useFlowState = (flowId: string) => {
  const [nodes, setNodes] = useState<Node[]>([])
  const [edges, setEdges] = useState<Edge[]>([])
  const [buildStatus, setBuildStatus] = useState<BuildStatus>(BuildStatus.IDLE)

  // Related state management logic here

  return { nodes, setNodes, edges, setEdges, buildStatus, setBuildStatus }
}

// Component becomes cleaner
const FlowPage: FC = () => {
  const { nodes, setNodes, edges, setEdges } = useFlowState(flowId)
  return <div>...</div>
}

Langflow Examples:

  • src/frontend/src/hooks/use-add-component.ts
  • src/frontend/src/hooks/use-unsaved-changes.ts
  • src/frontend/src/hooks/use-refresh-model-inputs.ts
Pattern 2: Extract Sub-Components

When: Single component has multiple UI sections, conditional rendering blocks, or repeated patterns.

Langflow Convention: Place sub-components in subdirectories or as separate files in the same directory. UI primitives go in components/ui/, domain components in components/core/, reusable components in components/common/.

typescript
// Before: Monolithic JSX with multiple sections
const GenericNode = () => {
  return (
    <div>
      {/* 100 lines of header UI */}
      {/* 100 lines of parameter fields */}
      {/* 100 lines of output handles */}
    </div>
  )
}

// After: Split into focused components
// CustomNodes/GenericNode/
//   generic-node.tsx       (orchestration only — kebab-case, descriptive name)
//   components/
//     node-header.tsx
//     node-parameters.tsx
//     node-outputs.tsx

const GenericNode = () => {
  return (
    <div>
      <NodeHeader nodeData={data} />
      <NodeParameters fields={fields} />
      <NodeOutputs outputs={outputs} />
    </div>
  )
}

Langflow Examples:

  • src/frontend/src/CustomNodes/GenericNode/components/
  • src/frontend/src/components/core/
  • src/frontend/src/components/ui/
Pattern 3: Simplify Conditional Logic

When: Deep nesting (> 3 levels), complex ternaries, or multiple if/else chains.

typescript
// Before: Deeply nested conditionals
const getFieldComponent = (field: InputFieldType) => {
  if (field.type === "str") {
    if (field.multiline) {
      return <TextAreaComponent />
    } else if (field.password) {
      return <PasswordInput />
    } else if (field.options?.length) {
      return <Dropdown options={field.options} />
    } else {
      return <InputComponent />
    }
  } else if (field.type === "int") {
    return <IntComponent />
  } else if (field.type === "float") {
    return <FloatComponent />
  }
  return null
}

// After: Use lookup tables + early returns
const FIELD_COMPONENT_MAP: Record<string, FC<FieldProps>> = {
  int: IntComponent,
  float: FloatComponent,
  bool: ToggleComponent,
  code: CodeAreaComponent,
}

const STR_VARIANT_MAP: Record<string, FC<FieldProps>> = {
  multiline: TextAreaComponent,
  password: PasswordInput,
  options: Dropdown,
}

const getFieldComponent = (field: InputFieldType) => {
  if (field.type !== "str") {
    const Component = FIELD_COMPONENT_MAP[field.type]
    return Component ? <Component {...field} /> : null
  }

  const variant = field.multiline ? "multiline"
    : field.password ? "password"
    : field.options?.length ? "options"
    : "default"

  const Component = STR_VARIANT_MAP[variant] ?? InputComponent
  return <Component {...field} />
}
Pattern 4: Extract API/Data Logic

When: Component directly handles API calls, data transformation, or complex async operations.

Langflow Convention:

  • This skill is for component decomposition, not query/mutation design.
  • When refactoring data fetching, use frontend-query-mutation for query patterns, UseRequestProcessor, cache invalidation, and mutation error handling.
  • Do not create thin passthrough useQuery wrappers during refactoring; only extract a custom hook when it truly orchestrates multiple queries/mutations or shared derived state.
  • API hooks live in controllers/API/queries/{domain}/.

Langflow Examples:

  • src/frontend/src/controllers/API/queries/flows/use-post-add-flow.ts
  • src/frontend/src/controllers/API/queries/variables/use-get-global-variables.ts
  • src/frontend/src/controllers/API/queries/folders/use-get-folders.ts
Pattern 5: Extract Modal/Dialog Management

When: Component manages multiple modals with complex open/close states.

Langflow Convention: Modals should be extracted with their state management.

typescript
// Before: Multiple modal states in component
const FlowToolbar = () => {
  const [showExportModal, setShowExportModal] = useState(false)
  const [showShareModal, setShowShareModal] = useState(false)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [showApiModal, setShowApiModal] = useState(false)
  // 5+ more modal states...
}

// After: Extract to modal management hook
type ModalType = "export" | "share" | "delete" | "api" | null

const useFlowToolbarModals = () => {
  const [activeModal, setActiveModal] = useState<ModalType>(null)

  const openModal = useCallback((type: ModalType) => setActiveModal(type), [])
  const closeModal = useCallback(() => setActiveModal(null), [])

  return {
    activeModal,
    openModal,
    closeModal,
    isOpen: (type: ModalType) => activeModal === type,
  }
}
Pattern 6: Extract Form Logic

When: Complex form validation, submission handling, or field transformation.

Langflow Convention: Extract form state and validation into hooks.

typescript
// Extract form validation and submission
const useFlowSettingsForm = (initialValues: FlowSettings) => {
  const [values, setValues] = useState(initialValues)
  const [errors, setErrors] = useState<Record<string, string>>({})

  const validate = useCallback(() => {
    const newErrors: Record<string, string> = {}
    if (!values.name?.trim()) newErrors.name = "Name is required"
    if (values.endpoint_name && !/^[a-z0-9-]+$/.test(values.endpoint_name)) {
      newErrors.endpoint_name = "Must be lowercase alphanumeric with hyphens"
    }
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }, [values])

  const handleChange = useCallback((field: string, value: any) => {
    setValues((prev) => ({ ...prev, [field]: value }))
  }, [])

  return { values, errors, validate, handleChange }
}

Langflow-Specific Refactoring Guidelines

1. Zustand Store Selectors

When: Component reads many values from a Zustand store, causing unnecessary re-renders.

typescript
// Before: Selecting too many values
const Component = () => {
  const flowStore = useFlowStore()
  // Component re-renders on ANY store change
}

// After: Use individual selectors
const Component = () => {
  const nodes = useFlowStore((state) => state.nodes)
  const edges = useFlowStore((state) => state.edges)
  // Component only re-renders when nodes or edges change
}

Langflow Reference: All stores in src/frontend/src/stores/ follow this selector pattern.

2. Custom Node Components

When: Refactoring flow node components (CustomNodes/GenericNode/).

Conventions:

  • Keep node logic in custom hooks
  • Extract parameter rendering to separate components
  • Use the existing components/ subdirectory for sub-components
CustomNodes/GenericNode/
  generic-node.tsx             # Node registration and main render (kebab-case, NOT index.tsx)
  components/
    handle-render.tsx           # Handle rendering
    node-description.tsx        # Node description display
    node-input-field.tsx        # Input field rendering
    node-name.tsx               # Node name display
    node-output-field.tsx       # Output field rendering
    node-status.tsx             # Build status display
3. Flow Canvas Components

When: Refactoring components related to the flow editor canvas.

Conventions:

  • @xyflow/react v12 is the canvas library
  • Keep canvas event handlers separate from UI rendering
  • Use useFlowStore for flow state management
  • Use useFlowsManagerStore for multi-flow management
Show full SKILL.md (312 more words)Show less
4. API Query Hook Components

When: Refactoring components that consume API data.

Conventions:

  • Use existing query hooks from controllers/API/queries/
  • Access UseRequestProcessor for new queries/mutations
  • Use query key arrays like ["useGetGlobalVariables"] for cache management
  • Cache invalidation belongs in mutation onSettled callbacks

Refactoring Workflow

Step 1: Assess Complexity

Manually count:

  • Total conditionals (if/else, switch, ternary, &&/||)
  • Maximum nesting depth
  • Total lines of code
  • Number of useState/useEffect hooks
  • Number of distinct UI sections
Step 2: Plan

Create a refactoring plan based on detected features:

Detected FeatureRefactoring Action
5+ useState hooks with related stateExtract custom hook
API calls in component bodyExtract to query hook
3+ event handlers with logicExtract event handlers to hook
300+ linesSplit into sub-components
Deep conditional nesting (>3)Simplify conditional logic
Multiple modal statesExtract modal management
Step 3: Execute Incrementally
  1. Extract one piece at a time
  2. Run lint, type-check, and tests after each extraction
  3. Verify functionality before next step
For each extraction:
  1. Extract code
  2. Run: npm run lint
  3. Run: npm run type-check
  4. Run: npm test
  5. Test functionality manually
  6. PASS? -> Next extraction
     FAIL? -> Fix before continuing
Step 4: Verify

After refactoring, re-assess complexity manually:

  • Target complexity < 50
  • Target line count < 300
  • Target max nesting depth <= 3
  • Target max function length < 30 lines

Common Mistakes to Avoid

Over-Engineering
typescript
// Too many tiny hooks
const useButtonText = () => useState("Click")
const useButtonDisabled = () => useState(false)
const useButtonLoading = () => useState(false)

// Cohesive hook with related state
const useButtonState = () => {
  const [text, setText] = useState("Click")
  const [disabled, setDisabled] = useState(false)
  const [loading, setLoading] = useState(false)
  return { text, setText, disabled, setDisabled, loading, setLoading }
}
Breaking Existing Patterns
  • Follow existing directory structures in components/ui/, components/core/, components/common/
  • Maintain naming conventions (kebab-case files, PascalCase components)
  • Preserve export patterns for compatibility
  • Keep Zustand store selector patterns consistent
Premature Abstraction
  • Only extract when there is clear complexity benefit
  • Do not create abstractions for single-use code
  • Keep refactored code in the same domain area
Bypassing UseRequestProcessor
  • Do not call useQuery or useMutation directly for API calls
  • Always use the UseRequestProcessor pattern for consistency with retry and invalidation logic
  • See frontend-query-mutation skill for API hook patterns

References

Langflow Codebase Examples
  • Hook extraction: src/frontend/src/hooks/
  • Component splitting: src/frontend/src/CustomNodes/GenericNode/components/
  • UI components: src/frontend/src/components/ui/
  • Core components: src/frontend/src/components/core/
  • Common components: src/frontend/src/components/common/
  • API query hooks: src/frontend/src/controllers/API/queries/
  • Zustand stores: src/frontend/src/stores/
  • frontend-query-mutation - For API query and mutation patterns
  • frontend-testing - For testing refactored components

© langflow-ai, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 3 other files (references) in .agents/skills/component-refactoring of langflow-ai/langflow.

  • SKILL.md
  • references/complexity-patterns.md
  • references/component-splitting.md
  • references/hook-extraction.md

Open the folder on GitHubat commit 504c02f

Compare with similar skills

Component Refactoring next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Component Refactoring compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Component Refactoring this skilllangflow-ai/langflow156k—~3.5kAutomated safety check: PassMIT
Component RefactoringPageAI-Pro/ralph-loop311—~1.8kAutomated safety check: PassMIT
Code Review And Qualityhylarucoder/hai-stack382—~934Automated safety check: PassMIT
Saleor App UIsaleor/apps162—~5.8kAutomated safety check: PassCustom licence
Vercel React Best Practicessanity-io/sanity6.4k130 repos~1.6kAutomated safety check: PassMIT
React Best Practicesmastra-ai/mastra29k—~1.9kAutomated safety check: PassCustom licence

Similar skills

  • Component Refactoring

    PageAI-Pro/ralph-loop

    Refactor high-complexity React components in frontend. An agent skill from PageAI-Pro/ralph-loop.

    311 GitHub stars~1.8k tokensUpdated 1 mo ago
    DevelopmentAuto-check passed
  • Code Review And Quality

    hylarucoder/hai-stack

    Reviews a code change for correctness, security, maintainability, architecture, performance, and verification gaps, or performs a local code-smell review.

    382 GitHub stars~934 tokensUpdated 3 days ago
    DevelopmentAuto-check passed
  • Saleor App UI

    saleor/apps

    Styling and layout guide for Saleor Apps using modern macaw-ui and @saleor/apps-ui-next.

    162 GitHub stars~5.8k tokensUpdated yesterday
    DevelopmentAuto-check passed
  • Official

    React and Next.js performance optimization guidelines from Vercel Engineering.

    6.4k GitHub starsUsed in 130 repos~1.6k tokens
    Frontend & DesignAuto-check passed
  • React Best Practices

    mastra-ai/mastra

    React performance optimization guidelines from Mastra Engineering.

    29k GitHub stars~1.9k tokensUpdated today
    Frontend & DesignAuto-check passed
  • No Use Effect

    mattiacerutti/supernova

    Enforce the no-useEffect rule when writing or reviewing React code.

    187 GitHub starsUsed in 2 repos~1.7k tokens
    DevelopmentAuto-check passed

More from langflow-ai/langflow

All 10 skills in this repo
  • Backend Code Review

    langflow-ai/langflow

    Review backend code for quality, security, maintainability, and best practices based on established checklist rules.

    156k GitHub stars~3.5k tokensUpdated today
    Auto-check: notes
  • E2E Testing

    langflow-ai/langflow

    Write and review Playwright E2E tests for Langflow. An agent skill from langflow-ai/langflow.

    156k GitHub stars~3.3k tokensUpdated today
    Auto-check passed
  • Frontend Query Mutation

    langflow-ai/langflow

    Guide for implementing Langflow frontend query and mutation patterns with Axios and TanStack React Query v5.

    156k GitHub stars~979 tokensUpdated today
    Auto-check passed
  • Ibm A11y Level1 Audit

    langflow-ai/langflow

    Perform a scoped IBM Equal Access Level 1 compliance audit of a chosen Langflow frontend surface (routes, components, or a PR) and produce a findings report mapped to WCAG/IBM Level 1 criteria.

    156k GitHub stars~2.4k tokensUpdated today
    Auto-check passed
  • Frontend I18n

    langflow-ai/langflow

    Add, change, or review user-facing text in the Langflow frontend using the i18n system (i18next / react-i18next).

    156k GitHub stars~1k tokensUpdated today
    Auto-check passed
  • Ibm A11y PR Remediation

    langflow-ai/langflow

    Scan every frontend surface touched by the current PR/branch for IBM Equal Access Level 1 accessibility issues and fix all in-scope violations by default.

    156k GitHub stars~2k tokensUpdated today
    Auto-check passed

Questions about Component Refactoring

What does Component Refactoring do?

Refactor high-complexity React components in Langflow frontend. Component Refactoring is an agent skill from langflow-ai/langflow. Refactor high-complexity React components in Langflow frontend.

When should I use Component Refactoring?

Component Refactoring fits situations like: manual complexity assessment shows complexity 50; the user asks for code splitting; hook extraction; complexity reduction.

How do I install Component Refactoring in Claude Code?

Run `npx skills add langflow-ai/langflow --skill component-refactoring -a claude-code`. Or copy the skill folder (.agents/skills/component-refactoring in langflow-ai/langflow) into .claude/skills/component-refactoring in your project. Claude Code loads it when a task matches its description.

How do I install Component Refactoring in Codex?

Run `npx skills add langflow-ai/langflow --skill component-refactoring -a codex`. Or copy the skill folder (.agents/skills/component-refactoring in langflow-ai/langflow) into .agents/skills/component-refactoring in your project. Codex loads it when a task matches its description.

Can I use Component Refactoring in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add langflow-ai/langflow --skill component-refactoring -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/component-refactoring, .gemini/skills/component-refactoring, .github/skills/component-refactoring and .opencode/skills/component-refactoring in your project.

What does Component Refactoring need to run?

Going by SKILL.md and its folder, Component Refactoring needs the command-line tools its instructions call (npm).

Does Component Refactoring access the network?

SKILL.md contains no URLs. Its commands use npm, which can reach the network depending on how they are called. This is read from the text; nothing was executed.

Is Component Refactoring safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Component Refactoring use?

Component Refactoring is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Component Refactoring use?

About 3.5k tokens (SKILL.md is roughly 14k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 11k tokens, read only when the agent opens those files.

What are the alternatives to Component Refactoring?

Skills that share tags, products or a category with Component Refactoring: Component Refactoring (PageAI-Pro/ralph-loop, 311 stars), Code Review And Quality (hylarucoder/hai-stack, 382 stars), Saleor App UI (saleor/apps, 162 stars) and Vercel React Best Practices (sanity-io/sanity, 6.4k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Component Refactoring?

langflow-ai (a GitHub organization) maintains it in langflow-ai/langflow, which has 155,573 GitHub stars. The repository holds 10 skills in this directory. The repository was last updated on October 8, 2026.

Source: langflow-ai/langflow on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.