Creating Data inside vs outside shiny... which is better

When creating a 'nonreactive' table such as the one below, is it better to create the table in the ui fluidpage, such as example 2, or to write the dataframe beforehand? Both work but I bet one is better practice than the other.

If I want to publish an app, does the data need to be called inside of the shiny code, such as example 2? I am new to shiny, so any insight would be much appreciated. Thanks!

## Example 1:
national_guidelines2023 <- data.frame(Persons = c(1, 2, 3, 4, 5, 6, 7, 8),
                                      PovertyGuidelines = c("$14,580", "$19,720", "$24,860", "$30,000", "$35,140", "$40,280", "$45,420", "$50,560"))
ui <- fluidPage(
  tableOutput("tabGuidelines")
)

server <- function(input, output) {

  output$tabGuidelines <- renderTable({
    national_guidelines2023
  })

}

shinyApp(ui, server)

## Example 2:
ui <- fluidPage(
  tableOutput("tabGuidelines")
)

server <- function(input, output) {
  
  output$tabGuidelines <- renderTable({
    national <- data.frame(Persons = c(1, 2, 3, 4, 5, 6, 7, 8), 
                           PovertyGuidelines = c("$14,580", "$19,720", "$24,860", "$30,000", "$35,140", "$40,280", "$45,420", "$50,560"))
    return(national)
                          
  })
  
}

shinyApp(ui, server)

There are probably differing schools of thought on this, but I am of the opinion that your better off creating the data outside your server IF AND ONLY IF your data is completely static (i.e. you don't query a database or make an API call based on parameters provided by the user). My reasoning for this is because of Shiny's reactivity. It's not the case that your code in a server function always executes top to bottom - it depends on things like invalidation. Because of this, reasoning about when certain parts of your server function run isn't always the most straightforward exercise. Because of that, it is possible, especially as your apps get more complex, that you accidentally have server code that runs more often than you might think, which means that your app has to build your dataset many times before just rendering it.

That is very helpful, thank you for your insight!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.