R Shiny Masterclass Top 10 Tips
1 – Don't make a monolith
Try to avoid writing your Shiny app in one large app.R file whenever possible!
Use a global.R, ui.R and server.R as the backbone of your Shiny application for clear separations of responsibility. Keep these files minimal - don’t be afraid to split out code into different files and folders for clarity!
2 – Modularise your Shiny applications!
Modularising parts of your Shiny app makes it easy to re-use code and UI elements across different areas of your Shiny app, without worrying about your inputs or outputs clashing with each other!
3 – Limit input values!
The more freedom the user has with inputs to your Shiny app, the more validation your code has to do!
Limit users to appropriate values with inputs like sliders (for numbers) or dropdown lists, checkboxes or radio buttons (for text).
Avoid open ended inputs like free text or file uploads, as these can require a lot more validation!
4 – Reactivity is lazy and you should be too!
Remember that reactivity in Shiny is lazy – it will only run reactive code when those results are needed somewhere in your application.
Reactives in Shiny will store results until the next time some reactive input changes – take advantage of this with multiple staged reactives to minimise processing time in your code.
5 – Avoid expensive processing in your Shiny apps
Try to do most of your data processing ahead of time, use your Shiny apps to focus on displaying the already processed outputs!
6 – Delay reactions
If you have a lot of inputs that affect some visualisation in your Shiny app, consider including some ‘Run’ button and using the isolate() function around those other reactive inputs, so that your user can apply all of their changes at once when that button is clicked!
7 – Take advantage of custom Shiny UI functions
The pre-made Shiny UI layouts are great, but not the only tool in our UI toolbox. We can also build up our UI using Shiny UI functions and CSS style sheets. Use a combination of Shiny UI layouts and HTML tag functions to create your interface, apply classes and IDs to your interface elements, then style those to your heart’s content with CSS!
8 – Manage ‘no data’ in your Shiny applications
Use the ‘req’ function to prevent reactive code from running before all of its required inputs are ready. Use the ‘validate’ function to provide some visual (and customisable, with CSS!) messages when some conditions aren’t met. This will allow you to insulate your users from any errors or unexpected behaviour due to lack of available data.
10 – Use reactlog to visualise reactivity in your Shiny application
It can be hard to visualise exactly what is happening behind the scenes with reactivity. The reactlog package is a great tool for figuring out how your inputs, outputs and reactive functions all fit together in your Shiny application. Check it out at rstudio.github.io/reactlog/