# Real time collaboration

With a supported real-time back-end, you can have a full collaborative and real-time Spreadsheet. The UI is data agnostic, so both OT and CRDT data structures are supported.

SheetGrid exposes the following prop to highlight users in the canvas grid.

```tsx
const App = () => {
  const currentUserId = 1
  <SheetGrid
    users={
      [
        {
          userId: 1,
          title: 'Foo bar',
          // Active cell that will be highlighted
          activeCell: { rowIndex: 2, columnIndex: 3},
          // Which sheetID is currently in focus
          sheetId: 1
        },
        {
          userId: 2,
          title: 'Foo bar',
          activeCell: { rowIndex: 2, columnIndex: 3},
          sheetId: 1
        }
      ]
    }
    userId={currentUserId}
  />
}
```

## Immer and useSpreadsheetState

If you are using `useSpreadsheetState` hook to manage the state of Spreadsheet, Immer is the state library that is used to modify state.

Immer has really good API for JSON patches that is sent over the wire for real-time collaboration. JSON patches also helps in building a robust undo/redo functionality.

`onChangeHistory` callback is fired when user modifies state.

```tsx
import { SpreadsheetProvider, CanvasGrid } from "@rowsncolumns/spreadsheet";
import { tokenize as tokenizer } from "@rowsncolumns/calculator";
import { useSpreadsheetState } from "@rowsncolumns/spreadsheet-state";

const MySpreadsheet = () => {
  const {} = useSpreadsheetState({
    onChangeHistory(patches) {
      // Send this over the wire to Yjs, Pusher, Liveblocks etc
      console.log(patches);
    },
  });
  return (
    <CanvasGrid
      rowCount={1000}
      columnCount={1000}
      sheetId={1}
      tokenizer={tokenizer}
      users={[{ ... }]}
      userId={}
    />
  );
};

const App = () => (
  <SpreadsheetProvider>
    <MySpreadsheet />
  </SpreadsheetProvider>
);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.rowsncolumns.app/collaboration/real-time-collaboration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
