JUCE ValueTree Part 2: State Management with CachedValue
In part 1 we explored the basics of juce::ValueTree. Now let's dive deeper into one of its most powerful companions: juce::CachedValue. This clever class creates a seamless bridge between your application variables and ValueTree data, making state management almost effortless.
What is CachedValue?
juce::CachedValue is a template class that holds a local copy of a value while keeping it synchronized with a ValueTree property. Think of it as a "smart variable" that automatically updates both ways – when the ValueTree changes, your cached value updates, and when you modify the cached value, the ValueTree reflects the change.
referTo()
The referTo() method creates a live connection between your variable and a specific property in a ValueTree:
cachedValue.referTo(valueTree, propertyIdentifier, undoManager);
This single line establishes a bidirectional sync that handles change notifications, type conversions, and even undo/redo functionality.
Building a Simple AppState
Let's create a practical example with an audio application state that manages common parameters:
class AppState
{
public:
AppState()
{
// Initialize the root ValueTree
state = juce::ValueTree("AppState");
// Connect all cached values to the state
setupCachedValues();
// Set some default values
setDefaults();
}
// Public interface - use these like normal variables!
juce::CachedValue<float> masterVolume;
juce::CachedValue<bool> muteEnabled;
juce::CachedValue<juce::String> lastOpenedFile;
juce::CachedValue<int> bufferSize;
juce::CachedValue<double> sampleRate;
// Access to the underlying ValueTree for saving/loading
juce::ValueTree getState() { return state; }
void replaceState(const juce::ValueTree& newState)
{
state = newState;
setupCachedValues(); // Reconnect after replacing state
}
// Optional: Undo manager for parameter changes
void setUndoManager(juce::UndoManager* um)
{
undoManager = um;
setupCachedValues(); // Reconnect with undo support
}
private:
juce::ValueTree state;
juce::UndoManager* undoManager = nullptr;
void setupCachedValues()
{
// Connect each cached value to its property in the ValueTree
masterVolume.referTo(state, "masterVolume", undoManager);
muteEnabled.referTo(state, "muteEnabled", undoManager);
lastOpenedFile.referTo(state, "lastOpenedFile", undoManager);
bufferSize.referTo(state, "bufferSize", undoManager);
sampleRate.referTo(state, "sampleRate", undoManager);
}
void setDefaults()
{
// Set default values if they don't exist
if (!state.hasProperty("masterVolume"))
masterVolume = 0.75f;
if (!state.hasProperty("muteEnabled"))
muteEnabled = false;
if (!state.hasProperty("bufferSize"))
bufferSize = 512;
if (!state.hasProperty("sampleRate"))
sampleRate = 44100.0;
}
};
Using Your AppState
The beauty of this approach is how natural it feels to use:
class MyAudioApplication
{
public:
MyAudioApplication()
{
// Set up undo manager
appState.setUndoManager(&undoManager);
// Use the state like normal variables
setupAudio();
loadSettings();
}
void setupAudio()
{
// Read values naturally
audioDevice.setBufferSize(appState.bufferSize.get());
audioDevice.setSampleRate(appState.sampleRate.get());
// Modify values easily
appState.masterVolume = 0.8f; // Automatically updates ValueTree!
appState.muteEnabled = false;
}
void saveSettings()
{
auto xml = appState.getState().createXml();
xml->writeTo(getSettingsFile());
}
void loadSettings()
{
if (auto xml = juce::XmlDocument::parse(getSettingsFile()))
{
auto loadedState = juce::ValueTree::fromXml(*xml);
if (loadedState.isValid())
appState.replaceState(loadedState);
}
}
void handleVolumeSliderChanged(float newVolume)
{
// This change will be undoable!
appState.masterVolume = newVolume;
}
private:
AppState appState;
juce::UndoManager undoManager;
juce::File getSettingsFile()
{
return juce::File::getSpecialLocation(
juce::File::userApplicationDataDirectory)
.getChildFile("MyApp/settings.xml");
}
};
Advanced Tips
Type Safety: CachedValue handles type conversions automatically, but be mindful of precision loss when converting between numeric types.
Performance: CachedValue maintains a local copy, so reading values is very fast – perfect for audio thread access.
Nested States: You can create hierarchical state management by using child ValueTrees:
// Create separate sections
juce::ValueTree audioSettings = state.getOrCreateChildWithName("Audio", nullptr);
bufferSize.referTo(audioSettings, "bufferSize", undoManager);
Conclusion
By combining ValueTree with CachedValue, you get:
- Automatic synchronization between your variables and persistent state
- Built-in undo/redo functionality
- Easy serialization to XML or binary formats
- Thread-safe parameter access
- Clean, readable code that feels like working with normal variables
This pattern forms the backbone of robust JUCE applications, from simple plugins to complex DAWs.