---
product: "AG Studio"
title: "Sharing & Caching Data"
description: "Share AG Studio's built-in data engine across instances, or cache it across a Studio instance's lifecycle."
framework: react
version: "3.1.1"
related:
    - title: "Data Overview"
      url: "https://www.ag-grid.com/studio/archive/3.1.1/react/data/"
    - title: "Data Modelling"
      url: "https://www.ag-grid.com/studio/archive/3.1.1/react/data-modelling/"
    - title: "Loading Data"
      url: "https://www.ag-grid.com/studio/archive/3.1.1/react/loading-data/"
    - title: "Live Data"
      url: "https://www.ag-grid.com/studio/archive/3.1.1/react/live-data/"
llms: "https://www.ag-grid.com/studio/archive/3.1.1/llms.txt"
---

# Sharing & Caching Data

A Data Engine loads, processes, and caches data for Studio widgets.

Studio creates one automatically when you pass data sources via the `data` property, but you can create the built-in engine yourself to share it across instances, or cache it across a Studio instance's lifecycle.

## Built-in Engine

When you pass data sources directly to Studio, it creates a built-in Data Engine behind the scenes. Creating the engine externally with `createDataEngine(data)` gives you two benefits:

- **Sharing** - multiple Studio instances can point at the same engine, so they share a single copy of the data.
- **Caching across lifecycles** - the engine survives when Studio is destroyed and recreated, so data doesn't need to be re-fetched or reprocessed on remount.

#### Data Engine

```tsx
"use client";

import type {
  AgDataEngine,
  AgDataSourcesDefinition,
  AgReportState,
} from "ag-studio";
import { createDataEngine, enableStudioDevValidations } from "ag-studio";
import type { AgStudioRef } from "ag-studio-react";
import { AgStudio } from "ag-studio-react";
import React, {
  StrictMode,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { createRoot } from "react-dom/client";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableStudioDevValidations();
}

const StudioExample = () => {
  const studioRef = useRef<AgStudioRef>(null);
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const studioStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [data, setData] = useState<AgDataSourcesDefinition | AgDataEngine>();
  const [created, setCreated] = useState<boolean>(true);
  const initialState = useMemo<AgReportState>(
    () => ({
      pages: [
        {
          id: "page1",
          widgets: {
            "1": {
              type: "grid",
              dataMapping: {
                cols: [
                  { id: "medals.country" },
                  { id: "medals.sport" },
                  { id: "medals.gold", aggregation: "sum" },
                  { id: "medals.silver", aggregation: "sum" },
                  { id: "medals.bronze", aggregation: "sum" },
                  { id: "medals.total", aggregation: "sum" },
                ],
              },
            },
            "2": {
              type: "column-chart-grouped",
              dataMapping: {
                categoryKey: [{ id: "medals.country" }],
                valueKey: [
                  { id: "medals.gold", aggregation: "sum" },
                  { id: "medals.silver", aggregation: "sum" },
                  { id: "medals.bronze", aggregation: "sum" },
                ],
                tooltipKey: [],
              },
            },
          },
          widgetLayout: {
            "1": {
              xTrack: 0,
              yTrack: 0,
              xSpan: 24,
              ySpan: 16,
            },
            "2": {
              xTrack: 0,
              yTrack: 16,
              xSpan: 24,
              ySpan: 16,
            },
          },
        },
      ],
      selectedPageId: "page1",
      panels: {
        filters: {
          collapsed: true,
        },
        edit: {
          collapsed: true,
        },
      },
    }),
    [],
  );

  useEffect(() => {
    fetch("https://www.ag-grid.com/studio/archive/3.1.1/example-assets/olympic-winners.json")
      .then((resp) => resp.json())
      .then((data: any[]) =>
        setData(createDataEngine({ sources: [{ id: "medals", data }] })),
      );
  }, []);

  const recreate = useCallback(() => {
    setCreated((currentCreated) => !currentCreated);
  }, []);

  return (
    <div style={containerStyle}>
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        <div className="example-controls">
          <div className="controls-row">
            <button onClick={recreate}>
              {created
                ? "Destroy Studio Instance"
                : "Recreate with Data Engine"}
            </button>
          </div>
        </div>

        {created && (
          <AgStudio
            ref={studioRef}
            style={studioStyle}
            className="my-studio-container"
            data={data}
            initialState={initialState}
            mode={"edit"}
          />
        )}
        {!created && (
          <div className="my-studio-container">No current Studio instance</div>
        )}
      </div>
    </div>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <StudioExample />
  </StrictMode>,
);
```

[Live example: Data Engine](https://www.ag-grid.com/studio/archive/3.1.1/examples/sharing-caching-data/data-engine/reactFunctionalTs/)

```ts
const dataEngine = createDataEngine({
    sources: [{
        id: 'medals',
        data: [
            {
                year: 2000,
                sport: 'Swimming',
                country: 'United States',
                // ... other fields
            },
            // ... other rows
        ],
    }],
});
```

```jsx
const data = useMemo(() => { 
	return dataEngine;
}, []);

<AgStudio data={data} />
```

See [Loading Data](https://www.ag-grid.com/studio/archive/3.1.1/react/loading-data/) for the full range of data loading patterns.

`createDataEngine(data)` accepts a `data` object of type `AgDataSourcesDefinition`.

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `sources` | `AgDataSource<TRegistry>[]` |  | One or more data sources. |
| `relationships` | `AgRelationDefinition[]` |  | When using multiple related tables, this describes the fields that link the tables together. |
| `expressions` | `AgExpressionFieldDefinition<TRegistry, AgFormat<TRegistry>, any>[]` |  | Expression field definitions for calculated columns. |
| `formats` | `TRegistry["formats"]` |  | Overrides to existing formats, or additional custom formats. |
| `description` | `string` |  | AI-facing overview of the entire dataset: what it contains, what it's for, domain quirks. |
| `calendars` | `AgCalendar[]` |  | Named time dimensions (calendars) that supply date fragments and a continuous date spine. |
| `buckets` | `TRegistry["buckets"]` |  | Additional date-fragment bucket definitions to register alongside the built-in set (year, quarter, month, week, day, monthOfYear, dayOfWeek, …). Use this to add project-specific groupings such as `weekend`, `dayOfMonth`, or `hour` that the built-in registry does not include. Provide via `createBuckets` so type-level registry inference works correctly. |
| `options` | `AgDataSourcesOptions` |  | Engine-wide behavioural options, such as fan-out detection policy. |

## Retrieving the Engine

`api.getDataEngine()` returns the engine the Studio instance is using, whether Studio created it or you passed your own in. It returns `undefined` until the engine is in place, which it is by the time the `studioReady` event fires.

If Studio created the engine, it is released when that Studio instance is destroyed. To keep the engine alive across a destroy and recreate, or to share it between instances, create it with `createDataEngine()` as above and pass it via the `data` property.

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| `getDataEngine` | `Function` |  | Returns the data engine this Studio instance is currently using, or `undefined` if it does not have one. A Studio configured without the `data` property never has an engine, and one that is still loading does not have it yet - the engine is in place by the time the `studioReady` event fires. If Studio created the engine, its lifetime is tied to this Studio instance: the engine is released when Studio is destroyed. To keep an engine alive across a Studio instance being destroyed and recreated, or to share one engine between several instances, create it yourself with `createDataEngine()` and pass it via the `data` property. Studio then leaves it in your hands, and `getDataEngine()` returns that same engine. |

## Custom Engines

Sharing and caching, as described above, are features of the built-in engine only. For larger datasets, or when you want to replace query execution with a backend you already own, see the [Custom Engine](https://www.ag-grid.com/studio/archive/3.1.1/react/server-side-data/) guide in the Server-Side Data section.
