Patches
âš Since version 6 support for Patches has to be enabled explicitly by calling enablePatches()
once when starting your application.
During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer. This is a very powerful tool if you want to fork your state temporarily and replay the changes to the original.
Patches are useful in few scenarios:
- To exchange incremental updates with other parties, for example over websockets
- For debugging / traces, to see precisely how state is changed over time
- As basis for undo/redo or as an approach to replay changes on a slightly different state tree
To help with replaying patches, applyPatches
comes in handy. Here is an example how patches could be used to record the incremental updates and (inverse) apply them:
The generated patches are similar (but not the same) to the RFC-6902 JSON patch standard, except that the path
property is an array, rather than a string. This makes processing patches easier. If you want to normalize to the official specification, patch.path = patch.path.join("/")
should do the trick. Anyway, this is what a bunch of patches and their inverse could look like:
âš Note: The set of patches generated by Immer should be correct, that is, applying them to an equal base object should result in the same end state. However Immer does not guarantee the generated set of patches will be optimal, that is, the minimum set of patches possible. It depends often on the use case what is considered 'optimal', and generating the optimal set of patches is potentielly computationally very expensive. So in cases you might want to post process the generated patches, or compress them as explained below.
produceWithPatches
#
Instead of setting up a patch listener, an easier way to obtain the patches is to use produceWithPatches
, which has the same signature as produce
, except that it doesn't return just the next state, but a tuple consisting of [nextState, patches, inversePatches]
. Like produce
, produceWithPatches
supports currying as well.
Which produces:
For a more in-depth study, see Distributing patches and rebasing actions using Immer
Tip: Check this trick to compress patches produced over time.