skip to content

In a Rails app, when does a ViewComponent or Phlex component beat a partial, and what does adopting components cost the team?

level: seniorimportance: should knowfreq 34%

answer

  1. explicit inputs through initialize
  2. logic as methods you can unit-test
  3. render? and slots for variation
  4. helpers are no longer implicit
  5. instances are single-use

basics

~20 s

A component beats a partial for reused UI with logic or variants: inputs are explicit, logic lives in testable methods, and render_inline tests run without a browser. The cost is another dependency and convention, helpers reached explicitly, and single-use instances.

solid answer

~50 s

A partial reads locals, `local_assigns` and whatever instance variables are set, and its logic tends to drift into helpers; strict locals help, but the partial still has no methods of its own and is tested through controller or system tests. A ViewComponent or Phlex class takes its inputs through `initialize`, so a missing one fails as an `ArgumentError`, keeps presentation logic in methods, decides with `render?` whether to render, exposes regions through slots or block methods, and is unit-tested with `render_inline` in milliseconds. That pays off for widgets reused across pages with states and variants: the claims portal's alert box and claim card. A one-off fragment of one page stays a partial. The costs: a gem and a second view style to learn, app helpers that must be reached explicitly (`helpers.` in ViewComponent, adapters in Phlex), instances that cannot be reused (`ViewComponent::ReusedInstanceError`, `Phlex::DoubleRenderError`), and wrapper components that add a class but no contract.

code

ruby · 18 lines
ruby
# A reused alert with logic and a render decision
class AlertComponent < ViewComponent::Base
  KINDS = %i[info warning error].freeze

  def initialize(kind:, message:)
    raise ArgumentError, "unknown kind #{kind}" unless KINDS.include?(kind)
    @kind = kind
    @message = message
  end

  def render? = @message.present?

  def css_class = "alert alert--#{@kind}"
end

# Wrong: one instance rendered for every claim raises on the second render
# alert = AlertComponent.new(kind: :warning, message: "Missing document")
# @claims.each { |claim| render(alert) }

go deeper

for a junior

Know that partials and components both reuse markup and that components take their inputs through new.

for a middle

Compare inputs, logic placement and testing between a partial with strict locals and a component, with one example of each.

for a senior

Name the signals for converting a fragment, the helper and single-use costs, and how to introduce components incrementally in a live app.

for a principal

Set the view-layer convention across teams: partials, ViewComponent or Phlex, a design-system catalogue, and who owns shared components.

## What a partial gives you, and what it does not A partial such as `app/views/claims/_card.html.erb` is the built-in way to reuse markup. It receives **locals**, can read `local_assigns` and, unless someone is careful, the instance variables of whatever action rendered it. Strict locals (`<%# locals: (claim:) -%>`) now let a partial declare its inputs, which closes the worst gap. What a partial still lacks: - **no methods of its own**: conditional classes, formatting and permission checks end up inline in ERB or in global helpers; - **no isolated test**: it is exercised through a controller, integration or system test, with routing and data setup; - **no lifecycle hooks** such as "render nothing when there is no message". ## What a component adds A **ViewComponent** (Ruby class plus sidecar template) or a **Phlex** class (Ruby only) turns the same fragment into an object: 1. **Explicit inputs.** `AlertComponent.new(kind:, message:)`; forgetting one is an `ArgumentError` at the call site, not a `nil` deep in the template. 2. **Methods for logic.** `css_class`, `status_label` and `can_approve?` are ordinary methods, private if you like, instead of ERB conditionals or app-wide helpers. 3. **A render decision.** `render?` returning `false` removes the alert box entirely when there is nothing to say. 4. **Regions.** ViewComponent's `renders_one` and `renders_many` give the claim card a header and actions; in Phlex, public methods that take blocks play that role. 5. **Unit tests.** `render_inline(ClaimCardComponent.new(claim:))` plus `assert_selector` runs in milliseconds with no browser; previews show every state to designers. 6. **Plain objects to render.** A ViewComponent template is compiled into a method on the component class, and a Phlex class is ordinary Ruby, so rendering is a method call on an object you can construct anywhere, including a test. ## Where each fits | Situation | Better fit | Why | |---|---|---| | One-off section of one page | partial | no reuse, little logic | | Fragment rendered in a collection, simple markup | partial with strict locals | built-in, collection rendering | | Widget reused across pages with states (alert box) | component | inputs, `render?`, tests | | Layout widget with caller-filled regions (claim card) | component with slots | slots keep the layout in one place | | Design system shared by several teams | components plus previews | catalogue and contract | ## What adopting components costs - **A dependency and a second view style.** Developers must know when to write a partial and when a component; mixing both without a rule produces both, inconsistently. - **Helpers are not implicit.** ViewComponent includes Action View's helpers but reaches `app/helpers` through `helpers.` (raising `HelpersCalledBeforeRenderError` before rendering); Phlex needs an adapter module or `register_*_helper` for each one. - **Single-use instances.** Building one component and rendering it in a loop raises `ViewComponent::ReusedInstanceError` (since 4.14) or `Phlex::DoubleRenderError`; create one instance per render or use `with_collection`. - **Upgrade churn.** ViewComponent 4 renamed its generator and configuration; Phlex 2 renamed `template` to `view_template`. - **Wrapper components.** A component that only renders a partial adds a class without adding a contract. ## Judgement in an interview A strong answer does not declare a winner. It names the signal for moving a fragment into a component: it is rendered from several places, it has conditional logic or states worth testing, or other teams consume it. It also names the signal for leaving it alone: a fragment that belongs to one page and has no logic. A good answer adds that ViewComponent keeps markup in templates that designers can still edit, while Phlex moves markup into Ruby, which suits Ruby-heavy teams better than template-editing ones. ## Mistakes interviewers listen for - **"Components replace partials."** They complement them; the decision is per fragment. - **"Components can read controller state like partials."** They see only their inputs, which is the point. - **"Build once, render many."** Both gems refuse a second render of one instance. - **"Helpers just work."** Only Action View's own helpers do in ViewComponent; app helpers need `helpers.` or an include, and Phlex needs adapters. - **"Components fix N+1 queries."** A component renders what it is given; loading data efficiently remains the controller's and the query's job.

  • Do strict locals make components unnecessary?
    No. Strict locals give a partial declared inputs and defaults, which removes the instance-variable leakage. A component still adds methods for its logic, a `render?` decision, slots, and `render_inline` unit tests; for a one-page fragment with little logic, a strict-locals partial is enough.
  • How would you introduce components into an existing app without a rewrite?
    Start with the most reused, most stateful fragments, such as the alert box and the claim card, and keep one-off partials. Add previews and `render_inline` tests as each is converted, set a base class for shared helpers, and write down the rule for when new UI becomes a component.

A partial is a photocopied form anyone can scribble extra fields onto; a component is a printed form with labelled boxes and a checklist on the back, so you can verify a filled-in copy without filing it.

  • Every partial should become a component
  • Components can read the controller's instance variables like partials can
  • One component instance can be built once and rendered in a loop
  • Components need system tests because they cannot be rendered alone
  • App helpers are available inside components exactly as in partials

Assumes ViewComponent 4.15 and Phlex 2.4 on Rails 8.1, where partials have strict locals; ViewComponent raises ReusedInstanceError since 4.14.