Recording and replaying code changes.

I am trying to figure out how can record and replay an array of ChangeSet (or is there a better way?).
In my current implementation I am using a cursor state (ReactJS state) to track where state lies at any point of time, in ChangeSet[]. Based on new state I am able to determine if inverted or actual changesets are needed to be applied.
Moving forward and backward through changes slowly works fine, but when called too frequently, this error is thrown:

Unhandled Rejection (RangeError): Applying change set to a document with the wrong length

I am currently using something like this:

 useEffect(() => {
        updateEditor()
    }, [cursor])

function updateEditor() {
        if (lastCursor > cursor) {
            for (let i = lastCursor; i > cursor; i--) {
                codemirror.view.dispatch({
                    changes: editStream[i].invert()
                })
            }
        } else {

            for (let i = lastCursor + 1; i <= cursor; i++) {
                codemirror.view.dispatch({
                    changes: editStream[i]
                })
            }
        }
    }

Is there a better way of handling this usecase?

Yes, you can use change sets to move forward and backward through history like this. The error you’re getting happens when you somehow try to apply a changeset to a document that doesn’t match the document it was created for (in length), which suggests some issue in your implementation.