# AdapTable React Hooks

Canonical page: https://www.adaptabletools.com/docs/react-adaptable-hooks

- AdapTable provides 3 useful React hooks
- These allow developers to access AdapTable State, Layouts and API from within their custom components

AdapTable React provides 3 React hooks, for developers to leverage in their React components.

These can be used anywhere inside the `<Adaptable.Provider />` component

The 3 React hooks are:

- `useAdaptableState`
- `useCurrentLayout`
- `useAdaptableApi`

**Example: Using the useAdaptableState and useCurrentLayout hooks**

Using the `useAdaptableState` and `useCurrentLayout` hooks

- This example leverages AdapTable's react hooks
- It shows how you can use the custom react hooks to access AdaptableState in a bespoke component outside of AdapTable (but inside the `<Adaptable.Provider />`)
- We provide a custom component that leverages the `useAdaptableState` React hook to retrieve (and display) the 3 Layouts in the State, and the `useCurrentLayout` to set the Layout

Demo project (React); the files without a marker are shown below:

```text
src/
  agGridModules.ts     [template]
  App.tsx
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.tsx            [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#react).

**`src/App.tsx`**

```ts
import * as React from 'react';
import {useMemo, useRef} from 'react';
import {
  Adaptable,
  AdaptableOptions,
  AdaptableReadyInfo,
  AdaptableApi,
  useAdaptableState,
  useCurrentLayout,
} from '@adaptabletools/adaptable-react-aggrid';

// import adaptable css
import '@adaptabletools/adaptable-react-aggrid/index.css';
// import aggrid themes (using Balham theme)

import './styles.css';
import {agGridModules} from './agGridModules';
import {GridOptions} from 'ag-grid-enterprise';
import {onAdaptableReady} from './onAdaptableReady';
import {WebFramework} from './rowData';
import {gridOptions} from './gridOptions';

function CustomLayoutSelectorComponent() {
  const layouts = useAdaptableState(state => state.Layout.Layouts || []);
  const [currentLayout, setCurrentLayout] = useCurrentLayout();

  if (!currentLayout || !layouts) {
    return null;
  }

  return (
    <div style={{display: 'flex', flexFlow: 'row', gap: 10, padding: 10}}>
      <span>Current Layout: </span>
      <select
        title="Select Layout"
        value={currentLayout.Name}
        onChange={e => setCurrentLayout(e.target.value)}>
        {layouts.map(layout => (
          <option key={layout.Name} value={layout.Name}>
            {layout.Name}
          </option>
        ))}
      </select>
    </div>
  );
}

const App: React.FunctionComponent = () => {
  const adaptableApiRef = useRef<AdaptableApi | null>(null);

  // adaptableOptions prop is only evaluated once, at initialisation
  // even if you create a new AdaptableOptions object, Adaptable won't use the latest reference
  // so instead, we need to reference the latest values inside the functions defined in the AdaptableOptions object
  const adaptableOptions: AdaptableOptions<WebFramework> = useMemo(
    () => ({
      primaryKey: 'id',
      adaptableId: 'AdapTable React Hooks',
      initialState: {
        Layout: {
          CurrentLayout: 'Grouped Layout',
          Layouts: [
            {
              Name: 'Table Layout',
              TableColumns: ['name', 'language', 'github_stars'],
            },
            {
              Name: 'Pivot Layout',
              PivotColumns: ['language'],
              PivotAggregationColumns: [
                {
                  ColumnId: 'github_stars',
                  AggFunc: 'avg',
                },
              ],
            },
            {
              Name: 'Grouped Layout',
              TableColumns: [
                'name',
                'language',
                'github_stars',
                'github_watchers',
                'subscribersRatio',
                'comments',
                'open_pr_count',
                'closed_issues_count',
                'created_at',
                'updated_at',
                'pushed_at',
                'license',
                'created_at',
                'has_wiki',
              ],
              RowGroupedColumns: ['license'],
              TableAggregationColumns: [
                {
                  ColumnId: 'github_stars',
                  AggFunc: 'sum',
                },
              ],
              SuppressAggFuncInHeader: true,
            },
          ],
        },
      },
    }),
    []
  );

  const agGridOptions: GridOptions<WebFramework> = useMemo(
    () => gridOptions,
    []
  );

  return (
    <div style={{display: 'flex', flexFlow: 'column', height: '100vh'}}>
      <Adaptable.Provider
        gridOptions={agGridOptions}
        adaptableOptions={adaptableOptions}
        modules={[...agGridModules]}
        onAdaptableReady={(adaptableReadyInfo: AdaptableReadyInfo) => {
          adaptableApiRef.current = adaptableReadyInfo.adaptableApi;
          onAdaptableReady(adaptableReadyInfo);
        }}>
        <CustomLayoutSelectorComponent />
        <Adaptable.UI style={{flex: 'none'}} />
        <Adaptable.AgGridReact />
      </Adaptable.Provider>
    </div>
  );
};
export default App;
```



## useAdaptableState Hook

The `useAdaptableState(selector?, equalityFn?)` hook will give you access to the whole of [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md).

```tsx
import { useAdaptableState } from '@adaptabletools/adaptable-react-aggrid';
```

The hook will return `null` if AdapTable is not yet ready

Additionally, you can use the hook with a selector to select just part of AdapTable State. An optional second argument is a React-Redux equality function:

```tsx {2,5}
// get Current Theme
const currentTheme = useAdaptableState(state => state.Theme.CurrentTheme);

// get Layout State
const layoutState = useAdaptableState(state => state.Layout);
```

## useCurrentLayout Hook

[Layouts](https://www.adaptabletools.com/docs/handbook-layouts/index.md) (and particularly the Current Layout) are central to AdapTable and regularly accessed.

For this reason AdapTable offers the `useCurrentLayout()` hook which allows developers to access the Current Layout (and also have a setter function).

```tsx
const [layout, setCurrentLayout] = useCurrentLayout();
```

The hook returns a tuple array:

- the current Layout
- a setter function that expects, as sole argument, the name of the Layout you want to apply

Ensure that the Layout is defined in your [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md)

The hook can be used like this:

```tsx {2,10,13}
function MyCmp() {
  const [currentLayout, setCurrentLayout] = useCurrentLayout();

  if (!currentLayout) {
    return null;
  }

  return (
    <div>
      Current layout {currentLayout.Name}
      <button
        onClick={() => {
          setCurrentLayout('MyPivotLayout');
        }}>
        Set pivot layout
      </button>
    </div>
  );
}
```

When AdapTable is not ready, the first element of the tuple is `null`

## useAdaptableApi hook

The `useAdaptableApi` hook returns a reference to the [Adaptable API](https://www.adaptabletools.com/docs/technical-reference-adaptable-api/index.md) (or `null` if AdapTable is not yet ready).

```tsx
import { useAdaptableApi } from '@adaptabletools/adaptable-react-aggrid';

function MyCmp() {
  const adaptableApi = useAdaptableApi();

  if (!adaptableApi) {
    return null;
  }

  return (
    <button
      onClick={() => {
        adaptableApi.layoutApi.setLayout('MyPivotLayout');
      }}>
      Set pivot layout
    </button>
  );
}
```
