shiny reactive, reactiveValue and eventReactive, observe and observeEvent in Shiny reactiveValues


Example

reactiveValues can be used to store objects, to which other expressions can take a dependency.

In the example below, a reactiveValues object is initialized with value "No text has been submitted yet.". A separate observer is created to update the reactiveValues object whenever the submit button is pressed. Note that the reactiveValues itself does not take a dependency on the expressions in its body.

library(shiny)

ui <- fluidPage(
  headerPanel("Example reactiveValues"),
  
  mainPanel(
    
    # input field
    textInput("user_text", label = "Enter some text:", placeholder = "Please enter some text."),
    actionButton("submit", label = "Submit"),
    
    # display text output
    textOutput("text"))
)

server <- function(input, output) {
  
  # observe event for updating the reactiveValues
  observeEvent(input$submit,
               {
    text_reactive$text <- input$user_text
  })
  
  # reactiveValues
  text_reactive <- reactiveValues(
    text = "No text has been submitted yet."
  )
  
  # text output
  output$text <- renderText({
    text_reactive$text
  })
}

shinyApp(ui = ui, server = server)