Reactivity 101

Case Studies: Building Web Applications with Shiny in R

Dean Attali

Shiny Consultant

Reactivity basics

  • Shiny uses reactive programming
  • Outputs react to changes in input
  • When value of variable x changes, anything that relies on x is re-evaluated
  • Contrast with regular R:

    x <- 5
    y <- x + 1
    x <- 10
    
  • What is the value of y? 6 or 11?

Case Studies: Building Web Applications with Shiny in R

Reactive variables

  • All inputs are reactive
  • input$<inputId> inside render function will cause output to re-render

    output$my_plot <- renderPlot({
        plot(rnorm( input$num ))
    })
    
  • output$my_plot depends on input$num

    • input$num changes ⇒

      output$my_plot reacts

Case Studies: Building Web Applications with Shiny in R

Reactive contexts

  • Reactive values can only be used inside reactive contexts
  • Any render*() function is a reactive context
  • Accessing reactive value outside of reactive context ⇒ error
server <- function(input, output) { 
    print(input$num)
}
ERROR: Operation not allowed without an active reactive context.
Case Studies: Building Web Applications with Shiny in R

Observe a reactive variable

  • observe({ ... }) to access reactive variable

    server <- function(input, output) { 
        observe({ 
            print( input$num )  
        }) 
    }
    
  • Useful for debugging, track reactive variable

  • Each reactive variable creates a dependency
observe({ 
    print( input$num1 ) 
    print( input$num2 )
})
Case Studies: Building Web Applications with Shiny in R

Create a reactive variable

  • reactive({ ... }) to create reactive variable

  • Wrong:

    server <- function(input, output) {
        x <- input$num + 1
    }
    
    ERROR: Operation not allowed without an active reactive context.
    
  • Correct:

    server <- function(input, output) { 
      x <- reactive({ 
          input$num + 1 
      })
    }
    
Case Studies: Building Web Applications with Shiny in R

Reactive variables

  • Access custom reactive variable like a function:
    • add parentheses ()
server <- function(input, output){
    x <- reactive({
        input$num + 1
    }) 
    observe({ 
        print( input$num )
        print( x() ) 
    })
}
Case Studies: Building Web Applications with Shiny in R

Let's practice!

Case Studies: Building Web Applications with Shiny in R

Preparing Video For Download...