Chapter 18. Functions
As your app gets bigger, it will get harder and harder to hold all the pieces in your head, making it harder and harder to understand. In turn, this makes it harder to add new features and harder to find a solution when something goes wrong (i.e., it’s harder to debug). If you don’t take deliberate steps, the development pace of your app will slow, and it will become less and less enjoyable to work on.
In this chapter, you’ll learn how writing functions can help. This tends to have slightly different flavors for UI and server components:
-
In the UI, you have components that are repeated in multiple places with minor variations. Pulling out repeated code into a function reduces duplication (making it easier to update many controls from one place) and can be combined with functional programming techniques to generate many controls at once.
-
In the server, complex reactives are hard to debug because you need to be in the midst of the app. Pulling out a reactive into a separate function, even if that function is only called in one place, makes it substantially easier to debug, because you can experiment with computation independent of reactivity.
Functions have another important role in Shiny apps: they allow you to spread out your app code across multiple files. While you certainly can have one giant app.R file, it’s much easier to manage when spread across multiple files.
I assume that you’re already familiar with the basics of functions.1 The goal of this ...
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.