Chapter 3. Basic Reactivity

Introduction

In Shiny, you express your server logic using reactive programming. Reactive programming is an elegant and powerful programming paradigm, but it can be disorienting at first because it’s a very different paradigm to writing a script. The key idea of reactive programming is to specify a graph of dependencies so that when an input changes, all related outputs are automatically updated. This makes the flow of an app considerably simpler, but it takes a while to get your head around how it all fits together.

This chapter will provide a gentle introduction to reactive programming, teaching you the basics of the most common reactive constructs you’ll use in Shiny apps. We’ll start with a survey of the server function, discussing in more detail how the input and output arguments work. Next we’ll review the simplest form of reactivity (where inputs are directly connected to outputs) and then discuss how reactive expressions allow you to eliminate duplicated work. We’ll finish by reviewing some common roadblocks encountered by newer Shiny users.

The Server Function

As you’ve seen, the guts of every Shiny app look like this:

library(shiny)

ui <- fluidPage(
  # frontend interface
)

server <- function(input, output, session) {
  # backend logic
}

shinyApp(ui, server)

The previous chapter covered the basics of the frontend, the ui object that contains the HTML presented to every user of your app. The ui is simple because every user gets the ...

Get Mastering Shiny now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.