1.6 Reactive expressions

Key part of reducing duplication and ensuring you D-R-Y (Don’t-Repeat-Yourself)

Duplicated code is particularly bad for Shiny apps which can get cumbersome and more difficult to maintain and debug as they grow (Although the latest release of shiny does have some improved debugging tools)

Reactive expressions combines some of the same logic as variables and functions, but is a bit different as these do not work the same in shiny as normal R programming.

Create a reactive expression by wrapping a block of code in reactive({...}) and assigning it to a variable.

You can use the reactive expression like a standard function with one important difference - it only runs once and caches the result until the input is changed. So once it is initialised it will return some form of constant until it’s updated again.

The below code retrieves the dataset once, not twice

server <- function(input, output, session) {
  # Create a reactive expression
  dataset <- reactive({
    get(input$dataset, "package:datasets")
  })

  output$summary <- renderPrint({
    # Use a reactive expression by calling it like a function
    summary(dataset())
  })
  
  output$table <- renderTable({
    dataset()
  })
}