0Pricing
R Academy · Lesson

Reactive Programming Deep Dive

Understand reactive values, reactives, observers, and the reactive graph.

Reactivity: The Core Idea

Shiny's reactive programming model automatically tracks dependencies between computations. When an input changes, only the outputs that depend on it re-execute — nothing more. Understanding this dependency graph is the key to writing efficient, bug-free Shiny apps.

library(shiny)

# Simplest reactive relationship:
# output depends on input — Shiny tracks this automatically
server <- function(input, output, session) {
  output$result <- renderText({
    paste('You typed:', input$text_in)  # depends on text_in
  })
}

reactive({}) — Shared Computations

reactive({...}) creates a reactive expression whose result is cached and shared. If multiple outputs use the same expensive computation, wrap it in reactive() to compute it once per change rather than once per consumer. Call it like a function: data_subset().

server <- function(input, output, session) {
  # Computed once, shared by multiple outputs
  filtered_data <- reactive({
    subset(mtcars, cyl == input$cyl_select)
  })

  output$plot  <- renderPlot({ plot(filtered_data()$wt,
                                    filtered_data()$mpg) })
  output$table <- renderTable({ filtered_data() })
  # filtered_data() is only recomputed once when cyl_select changes
}

All lessons in this course

  1. Reactive Programming Deep Dive
  2. Shiny Modules for Code Reuse
  3. Dynamic UI with renderUI and insertUI
  4. Deploying Shiny Apps
← Back to R Academy