The Analogy: A Theatre Lighting Desk
Stand at the lighting desk at the back of a theatre. In front of you is a bank of faders, each a channel the operator can push up or pull down. Behind the desk, out of sight, runs the patch: a field of connections that decides which dimmers and which lamps on stage a given channel actually drives. And built on top of the channels are cues -- named combinations that say "for this moment in the show, these channels sit at these levels." The operator touches only the faders; the patch and the cues turn a fader move into light on the stage.
A Shiny application is that desk. The faders are the inputs -- the sliders, boxes, and buttons the user moves. The lamps on the stage are the outputs -- the plots, tables, and text the user sees rendered. The patch, the hidden field of connections, is the reactive dependency graph: it records which outputs draw on which inputs, so that a change to one fader reaches exactly the lamps wired to it and no others. The cues, the reusable mid-level combinations, are reactive expressions: named calculations that sit between the raw faders and the final lamps, built once and shared by everything downstream of them.
The magic of the desk is how a single fader move propagates. Push one channel up and power flows only along its patched lines; the lamps on those lines brighten, and every other lamp holds exactly where it was. Nothing recalculates the whole stage. Shiny works the same way: when an input changes, only the outputs and expressions that declared a dependency on that input are invalidated and recomputed, while everything else keeps its last value untouched. The dependency is declared simply by reading the input inside a reactive context -- reading a fader in a cue patches that cue to that fader automatically.
The failure mode is bad patching. Suppose the operator, instead of building one sub-master cue that dims the whole back wall and patching every output through it, wires the same dimming calculation separately into each lamp. Now one fader move makes the desk redo that identical calculation once for every lamp, and on a big rig the desk lags behind the operator's hands. A Shiny app makes the same mistake when several outputs each read an input and repeat the same expensive filtering inline, rather than sharing one reactive expression. Worse still is grabbing a live channel with no cue behind it -- reading a reactive value outside any reactive context -- which in Shiny is not a dim lamp but a hard error. The patch has rules, and fighting them is how a responsive desk turns sluggish or dark.
Syntax or Core Structure
A Shiny app has a UI that lays out the faders and lamps, and a server function that wires inputs to outputs. Output-rendering functions like renderText and renderPlot read inputs and produce values; reading input$x inside one of them patches that output to that input. You can exercise the server logic without a browser using shiny::testServer, which lets you set inputs and read the resulting outputs directly.
library(shiny)
carats <- c(0.3, 0.5, 0.8, 1.0, 1.2, 1.5, 2.0)
server <- function(input, output, session) {
output$kept <- renderText({
sum(carats >= input$threshold) # reading input$threshold patches this output to it
})
}
# testServer runs the server's reactive logic headlessly
testServer(server, {
session$setInputs(threshold = 1.0)
writeLines(sprintf("%-15s: %.1f", "threshold set", 1.0))
writeLines(sprintf("%-15s: %d", "stones total", length(carats)))
writeLines(sprintf("%-15s: %s", "stones kept", output$kept))
})
Output:
threshold set : 1.0
stones total : 7
stones kept : 4
Setting threshold to 1.0 through session$setInputs moves the fader, and reading output$kept pulls the lamp's current value: four of the seven stones have a carat of at least 1.0. The output rendered its count because it read input$threshold and was therefore patched to it; had the threshold never been set, reading the output would have failed for want of a value. testServer is the bench test of the desk -- it drives the faders and reads the lamps with no stage, no browser, and fully deterministic results.
Technical Depth: The Reactive Graph
Reactive expressions cache within a flush
A reactive() is a cue: a named calculation built once and shared. Its defining property is that it caches its value and recomputes only when a dependency invalidates it. If two outputs read the same reactive during one update cycle -- one flush -- the calculation runs once and both outputs get the cached result. This is the whole reason to reach for a reactive instead of repeating a calculation.
carats <- c(0.3, 0.5, 0.8, 1.0, 1.2, 1.5, 2.0)
runs <- 0
server <- function(input, output, session) {
kept <- reactive({ runs <<- runs + 1; sum(carats >= input$threshold) })
output$count <- renderText(kept()) # both outputs read the SAME reactive
output$label <- renderText(paste("kept:", kept()))
}
testServer(server, {
session$setInputs(threshold = 1.0)
k1 <- output$count # flush 1: two outputs, kept runs once
invisible(output$label)
session$setInputs(threshold = 0.5)
k2 <- output$count # flush 2: kept invalidated, runs once
invisible(output$label)
writeLines(sprintf("%-16s: %.1f", "first threshold", 1.0))
writeLines(sprintf("%-16s: %s", "kept at 1.0", k1))
writeLines(sprintf("%-16s: %.1f", "second threshold", 0.5))
writeLines(sprintf("%-16s: %s", "kept at 0.5", k2))
writeLines(sprintf("%-16s: %d", "reactive runs", runs))
writeLines(sprintf("%-16s: %d", "naive reads", 4L))
})
Output:
first threshold : 1.0
kept at 1.0 : 4
second threshold: 0.5
kept at 0.5 : 6
reactive runs : 2
naive reads : 4
Two outputs read kept() across two flushes, which is four reads in total, yet the reactive body ran only twice -- once per flush. Within a flush the second reader got the cached value, and the reactive recomputed only when threshold changed and invalidated it. Had each output filtered inline instead of sharing the reactive, the filter would have run all four times. The cache is what turns four reads into two computations.
The building blocks and when each fires
Shiny gives several reactive tools, and choosing the right one is choosing when the calculation fires and what it produces.
| Building block | Fires when | Produces |
|---|---|---|
| reactive | A dependency changes and its value is read | A cached value for others to read |
| observe | Any dependency changes | A side effect, no return value |
| eventReactive | A specified trigger fires | A cached value, ignoring other deps |
| observeEvent | A specified trigger fires | A side effect on that trigger only |
| render functions | A dependency changes | Output sent to the UI |
Dependency isolation: only patched lamps move
Because dependencies are tracked per expression, changing one input recomputes only the expressions that read it. An expression that never reads a given input is not patched to it and does not fire when it changes.
carats <- c(0.3, 0.5, 0.8, 1.0, 1.2, 1.5, 2.0)
kept_runs <- 0; label_runs <- 0
server <- function(input, output, session) {
kept <- reactive({ kept_runs <<- kept_runs + 1; sum(carats >= input$threshold) })
label <- reactive({ label_runs <<- label_runs + 1; toupper(input$currency) })
output$a <- renderText(kept())
output$b <- renderText(label())
}
testServer(server, {
session$setInputs(threshold = 1.0, currency = "usd")
invisible(c(output$a, output$b)) # initial flush: both run once
session$setInputs(threshold = 0.5) # change ONLY threshold
invisible(c(output$a, output$b))
writeLines(sprintf("%-18s: %s", "inputs", "threshold currency"))
writeLines(sprintf("%-18s: %s", "kept depends on", "threshold"))
writeLines(sprintf("%-18s: %s", "label depends on", "currency"))
writeLines(sprintf("%-18s: %s", "changed", "threshold"))
writeLines(sprintf("%-18s: %d", "kept runs", kept_runs))
writeLines(sprintf("%-18s: %d", "label runs", label_runs))
})
Output:
inputs : threshold currency
kept depends on : threshold
label depends on : currency
changed : threshold
kept runs : 2
label runs : 1
Both reactives ran once on the initial flush. Then threshold changed, and only kept -- which reads it -- recomputed; label reads currency alone, was not patched to threshold, and held its value. That selective propagation is the point of the graph: work is confined to the lamps wired to the fader that moved.
isolate: reading a fader without patching to it
Sometimes you want to read an input's current value without making the surrounding expression depend on it. isolate() does exactly that: it reads inside the reactive graph but takes no dependency, so a later change to that input does not trigger a recompute.
runs <- 0
server <- function(input, output, session) {
total <- reactive({ runs <<- runs + 1; input$a + isolate(input$b) })
output$sum <- renderText(total())
}
testServer(server, {
session$setInputs(a = 5, b = 10)
s0 <- output$sum # 5 + 10 = 15, runs = 1
session$setInputs(b = 20) # b is isolated: no recompute
s1 <- output$sum # still 15
session$setInputs(a = 8) # a is a dependency: recompute
s2 <- output$sum # 8 + current b (20) = 28
writeLines(sprintf("%-16s: %d", "a set", 5L))
writeLines(sprintf("%-16s: %d", "b set", 10L))
writeLines(sprintf("%-16s: %s", "sum shown", s0))
writeLines(sprintf("%-16s: %s", "change b to 20", s1))
writeLines(sprintf("%-16s: %d", "runs after b", 1L))
writeLines(sprintf("%-16s: %s", "change a to 8", s2))
writeLines(sprintf("%-16s: %d", "runs after a", runs))
})
Output:
a set : 5
b set : 10
sum shown : 15
change b to 20 : 15
runs after b : 1
change a to 8 : 28
runs after a : 2
After setting b to 20, the sum still reads 15: because b was read through isolate, changing it did not invalidate total, and the reactive did not run. Only when a -- a real dependency -- changed did total recompute, and at that point it read b's current value of 20, giving 28. The result is deliberately stale between the two events, which is precisely what isolate is for: pull in a value without letting it drive the update.
Real World Example: A Pricing Dashboard That Filters Twice
A jeweller's dashboard shows two things about a filtered set of stones: a plot of the kept stones and a summary line with their count and mean price. A slider sets the minimum carat. The obvious way to build it is to write the filter into each output -- the plot filters, and the summary filters -- and it works perfectly. It is also wired wrong: the same filter runs once for the plot and once for the summary on every single slider move, exactly the operator who patched one dimming calculation into each lamp instead of building one sub-master. The program below instruments the filter with a counter so the waste is visible.
library(shiny)
carats <- c(0.3, 0.5, 0.8, 1.0, 1.2, 1.5, 2.0)
prices <- c(300, 500, 800, 1000, 1200, 1500, 2000)
filter_runs <- 0
server <- function(input, output, session) {
# NO shared reactive: each output filters the data itself
output$plot_n <- renderText({
filter_runs <<- filter_runs + 1
idx <- carats >= input$threshold
sum(idx)
})
output$summary <- renderText({
filter_runs <<- filter_runs + 1 # the SAME filter, a second time
idx <- carats >= input$threshold
sprintf("%.2f", mean(prices[idx]))
})
}
testServer(server, {
session$setInputs(threshold = 1.0)
k1 <- output$plot_n; invisible(output$summary) # flush 1: filter runs twice
session$setInputs(threshold = 0.5)
k2 <- output$plot_n; mp <- output$summary # flush 2: filter runs twice more
writeLines(sprintf("%-19s: %s", "kept at 1.0", k1))
writeLines(sprintf("%-19s: %s", "kept at 0.5", k2))
writeLines(sprintf("%-19s: %s", "mean price kept", mp))
writeLines(sprintf("%-19s: %d", "outputs per flush", 2L))
writeLines(sprintf("%-19s: %d", "flushes", 2L))
writeLines(sprintf("%-19s: %d", "filter runs (inline)", filter_runs))
writeLines(sprintf("%-19s: %d", "filter runs (shared)", 2L))
})
Output:
kept at 1.0 : 4
kept at 0.5 : 6
mean price kept : 1166.67
outputs per flush : 2
flushes : 2
filter runs (inline): 4
filter runs (shared): 2
The dashboard produces correct numbers: four stones kept at a threshold of 1.0, six at 0.5, and a mean price of 1166.67 for the kept set. A tester glancing at the values would sign it off. The counter tells the other half of the story: across two slider moves the filter ran four times, twice per flush, because each output recomputed it independently. A single shared reactive filtering the data once per flush would have run it twice, half the work, and every output would have read the same cached result.
The flaw is a performance and correctness hazard hiding behind correct output, and it is worth naming precisely. The immediate cost is duplicated computation: the filter runs once per output rather than once per change, so the waste scales with the number of outputs. Swap the seven-element vector for a few hundred thousand rows and the inline filter for a database query, and every slider nudge fires that query once per output, and the desk lags visibly behind the operator's hand. The deeper hazard is correctness through divergence. Because the filtering logic is written out twice, the two copies can drift: a later edit that changes >= to > in one output but not the other leaves the plot and the summary describing different sets of stones, with nothing to flag the mismatch. A shared reactive removes both problems at once -- one definition, computed once, read everywhere -- which is why duplicated inline computation, not a wrong number, is the real defect in this otherwise working app.
Common Mistakes
- Repeating the same filter or query inline in several outputs. When each output reads an input and redoes the same expensive work, that work runs once per output on every change instead of once. Compute it in a single shared
reactiveand let every output read the cached result.
- Reading a reactive value outside a reactive context. Calling
input$xor areactive()at the top level of the server, or in a plain helper function, raises an error because there is no reactive context to track the dependency. Reactive values may only be read insidereactive,observe,renderfunctions, orisolate.
- Using
observewhere you meantreactive. Anobserveblock runs for its side effects and returns nothing, so trying to read its result gives you nothing. If you need a value that other expressions consume, usereactive; reserveobserveandobserveEventfor side effects like writing files or updating inputs.
- Forgetting that
reactiveis lazy. A reactive does not run until something reads it. Code that assumes a reactive has executed simply because it was defined -- for a side effect, say -- will find it never ran. Put side effects inobserve, which is eager, not inreactive.
- Creating an invalidation loop. An
observethat both reads an input and updates it, or two reactives that depend on each other, can trigger endless recomputation. Break the cycle withisolateon the value you only want to read, or restructure so the dependency runs one way.
- Doing heavy work in
renderPlotorrenderTableinstead of a reactive. Render functions rerun whenever their dependencies change, so expensive computation inside them repeats on every relevant input change and cannot be shared. Compute in a reactive and let the render function only draw.
- Overusing
reactivefor trivial expressions. Wrapping a cheap one-line calculation in its own reactive adds nodes to the graph and indirection to the code for no gain. Reserve reactives for work that is expensive, shared by multiple consumers, or genuinely stateful.
- Assuming inputs exist on the first run. Before the UI sends initial values,
input$xcan beNULL, and arithmetic or subsetting onNULLfails. Guard early reads withreq(input$x)so the output waits for a value rather than erroring on startup.
- Skipping
testServerand testing only by clicking. Manual clicking cannot count how often a reactive fires or prove that an output ignores an unrelated input.testServerdrives inputs and reads outputs deterministically, catching reactivity bugs that look fine in the browser.
Best Practices
- Compute each derived dataset once in a shared
reactiveand have every output read it, so a change recomputes the work a single time and all outputs stay consistent by construction.
- Keep render functions thin: let them draw or format, and push all filtering, joining, and modelling into reactives upstream. A render function should read a reactive and present it, nothing more.
- Choose the reactive tool by intent --
reactivefor a shared value,eventReactivefor a value computed on an explicit trigger,observeandobserveEventfor side effects -- so the graph expresses when each piece of work should fire.
- Guard reactive reads that can start out empty with
req, so outputs wait for their inputs to exist instead of throwing errors during the app's first render.
- Use
isolatedeliberately when you need an input's current value without depending on it, and comment why, since an isolated read is a dependency the graph will not show.
- Test server logic with
testServer, setting inputs and asserting on outputs and on how often instrumented reactives run, so reactivity is verified rather than eyeballed.
- Name reactives for the value they hold, not the widget that feeds them, so the graph reads as a pipeline of meaningful quantities and survives a change to the UI.
- Keep the dependency graph shallow and one-directional: avoid reactives that depend on each other in a cycle, and prefer a clear flow from inputs through shared reactives to outputs.
Practice Exercises
- Write a server with one input and one
renderTextoutput that reads it, then drive it withtestServer: set the input to two different values and confirm the output changes accordingly. Add a second input the output does not read, change it, and confirm the output stays the same.
- Refactor a server in which two outputs each filter the same vector inline so that both read a single shared
reactive. Add a counter to the filter and usetestServerto show the filter runs once per change rather than once per output.
- Build a reactive that reads one input directly and another through
isolate. UsingtestServer, change the isolated input and confirm the reactive does not recompute, then change the direct input and confirm it recomputes and picks up the isolated value's current setting.
- Add
reqto an output that reads an input which isNULLbefore the UI initialises. UsetestServerto read the output before setting the input and confirm it waits silently rather than erroring, then set the input and confirm the output appears.