Overview

By default, D3 visualizations created with r2d3 are monolithic scripts that do all of their work as a single computation (the body of the script). While this makes scripts straightforward to author by default, not all visualizations will confirm to this simple model. Rather, some visualizations will want to distinguish between the following activities:

1) Code that performs one-time initialization for the visualization (e.g. creation of a D3 layout).

2) Code that runs whenever the data underlying the visualization is changed.

This article describes how you can use the r2d3 advanced rendering API to organize your visualization code to run in this more granular fashion.

onRender Callback

To distinguish between code that runs at initialization-time only and code that runs when data changes, organize your code so that the code which responds to data changes is contained within the r2d3.onRender() callback. For example:

onResize Callback

By default, when the element which contains your visualization is resized, r2d3 will call back your script to re-render the visualization from scratch using the new size. In some cases this might be acceptable, but in other cases it makes sense to have code which explicitly handles the resize in a more efficient fashion.

You can provide an explicit resize handler by implementing the r2d3.onResize() callback. For example, in a force directed D3 layout you might do this in the onResize() callback: