# React integration

> Current Froomle documentation · [View canonical page](https://docs.froomle.com/froomle-doc-main/v2/js_lib/react.html)

Use the React bindings to fetch and track recommendations in browser components. Set the shared runtime state and [consent](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#Consent), mount `FroomleSdkInit` for page events, then [choose a recommendation hook](https://docs.froomle.com/froomle-doc-main/v2/js_lib/react.html#_supported_react_paradigms).

<a id="ReactBindings"></a>

## React Bindings

React helpers are exposed from `@froomle/frontend-sdk/react`. Use this layer when your recommendation blocks are React components instead of DOM templates with `data-froomle-…​`.

For list policy and React customer-item options, see [Benchmarking and A/B Testing with the SDK](https://docs.froomle.com/froomle-doc-main/v2/js_lib/benchmarking.html#BenchmarkingSdk).

> **NOTE:**
> 
> For setter scope, see [Runtime Scope Guide](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#RuntimeScope). React integrations still use shared page/app-level SDK state (`setEnvironment`, `setPageVisit`, `setChannel`, optional `setSiteContext` override or clear, `setSubscriptionLevel`, `setConsent`, `setDeviceId`, `setUserId`, `setContextItem`, `setContextItemType`), while each recommendation block/component supplies its own list/filter/rendering configuration.

> **TIP:**
> 
> Need a complete React example app instead of API snippets? Use [frontend-sdk-examples](https://bitbucket.org/froomle/frontend-sdk-examples). The examples repo includes React news, retail, and ArcXP examples.

> **IMPORTANT:**
> 
> React bindings are intended for the client-rendered / rehydrated React layer of your app.
> 
> -   Use this pattern in a browser entry such as `main.jsx`, or in a framework-specific client bootstrap that runs under the real React app root.
>     
> -   Do not mount `FroomleSdkInit` from a server-only shell, output type, or SSR template wrapper that never rehydrates on the client.
>     
> -   React bindings do not call `init()` and do not start declarative DOM placeholder mode.
>     
> -   A ready, mounted `FroomleSdkInit` owns automatic page tracking, while rendered `FroomleReco` placements register automatic recommendation tracking. Forward CMP changes through `setConsent(…​)`; do not remount components, refresh recommendations, or send raw manual events in the consent callback. React imports/hooks without `FroomleSdkInit` do not enable automatic page tracking. See [Automatic tracking after consent changes](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#consent-page-recovery).
>     
> -   Raw declarative `data-froomle-…​` blocks injected onto a React page stay idle unless you explicitly start DOM placeholder mode yourself. Mixing those modes on the same page is not the preferred integration path.
>     
> -   In hybrid frameworks, apply consent and identity in the browser integration. Supply the authenticated account and CMP state to the client bootstrap rather than relying on account or device cookies to substitute for these setters.
>     
> -   If you only need shell-level integration and automatic SDK-managed events (`page_visit`, `detail_pageview`, `impression`, `click_on_recommendation`), prefer [Script-Tag Setup](https://docs.froomle.com/froomle-doc-main/v2/js_lib/declarative-html.html#ScriptTagSetup) and the runnable plain HTML examples in [frontend-sdk-examples](https://bitbucket.org/froomle/frontend-sdk-examples) instead of forcing the React bindings into the server shell.
>     

<a id="react-startup"></a>

### Configure and mount the SDK

1.  Configure SDK once in the client entry (`main.jsx` in this example).
    
2.  Wrap the app with `FroomleSdkInit`.
    
3.  Choose one React rendering paradigm for each recommendation flow.
    
4.  Render each recommendation item through `FroomleReco` when you want automatic recommendation-item event tracking.
    
5.  Add advanced composition with `FroomleOrder` and `FroomleCustomItem`.
    

[Connect your consent manager](https://docs.froomle.com/froomle-doc-main/v2/js_lib/configuration.html#cmp-bridge) to apply the visitor’s current choice before mounting the app and forward later updates through `setConsent(…​)`.

```jsx
import React from 'react'
import ReactDom from 'react-dom/client'
import { setEnvironment, setPageVisit } from '@froomle/frontend-sdk'
import { FroomleSdkInit } from '@froomle/frontend-sdk/react'
import App from './App'

setEnvironment('sample_env')
setPageVisit('home')
// Apply your CMP's current consent choice before mounting the app.

ReactDom.createRoot(document.getElementById('root')).render(
  <FroomleSdkInit>
    <App />
  </FroomleSdkInit>
)
```

<a id="_choose_a_recommendation_hook"></a>

### Choose a recommendation hook

| Hook | Use it for | Render with |
| --- | --- | --- |
| [`useRecoList(…​)`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/react.html#react-reco-list) | One list of original CMS cards or Froomle recommendations. | FroomleReco entry={entry} for each selected entry. |
| [`useRecoEntry(…​)`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/react.html#react-reco-entry) | One recommendation slot with an original CMS card. | FroomleReco entry={entry} when the entry is not `null`. |
| [`useCreateReco(…​)`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/react.html#react-reco-slot) | One slot that displays a returned recommendation or stays empty. | FroomleReco reco={reco} with the returned handle. |
| [`useSmartSort(…​)`](https://docs.froomle.com/froomle-doc-main/v2/js_lib/smart-sorting-reranking.html#SmartSortReact) | Reranking items your application already has, such as search results. | FroomleReco entry={entry} for each selected candidate. |

Set `showFroomleContentFor` on a hook’s query to override the content policy for that list. Register any external group before startup; a list policy does not change it. For original cards, pass `customerItems` or `customerItem` and a stable `getId`; provide `getItemType` for non-article content. These options and `mapRecommendationItem` belong directly on the query.

<a id="_react_component_behavior"></a>

### React Component Behavior

<a id="react-reco-slot"></a>

#### `useCreateReco`

The hook returns a `RecommendationHandle` for one slot. React sends the requests automatically and batches compatible slots; there is no explicit flush. Pass the handle to `FroomleReco`. Inside the wrapper, `useReco()` gives you the handle and updates the rendered content when the item arrives. Fields such as `Id` are empty before a current recommendation is available.

```tsx
import { FroomleReco, useCreateReco, useReco } from '@froomle/frontend-sdk/react'

function RecommendationLink() {
  const reco = useReco()
  if (!reco.Id) return null

  return <a href={reco.get<string>('uri')}>{reco.get<string>('title')}</a>
}

export function SidebarRecommendation() {
  const reco = useCreateReco({ list: 'sidebar_recommendation' })
  return (
    <FroomleReco reco={reco}>
      <RecommendationLink />
    </FroomleReco>
  )
}
```

If you await the handle in application code, it resolves to an item when available, resolves to `null` when the customer experience is selected, and rejects with `No recommendation available` for a Froomle-experience slot with no item. Request failures also reject. Use `useRecoEntry(…​)` instead if this slot should show an original card when the policy selects customer content.

<a id="react-reco-list"></a>

#### `useRecoList`

Use `entries` for display. It contains original cards supplied via `customerItems` or Froomle items, optionally transformed by `mapRecommendationItem` into the same shape as your CMS cards. Pass each entry unchanged to `FroomleReco` and use its `item` for the visible content.

```tsx
import { FroomleReco, useRecoList } from '@froomle/frontend-sdk/react'

type Article = { id: string; title: string; url: string }
const size = 4

export function RelatedStories({ originals }: { originals: Article[] }) {
  const { entries, loading, status } = useRecoList({
    list: 'related_stories',
    limit: size,
    list_size: size,
    customerItems: {
      items: originals.slice(0, size),
      getId: article => article.id,
    },
    mapRecommendationItem: (reco): Article => ({
      id: reco.Id,
      title: reco.get<string>('title'),
      url: reco.get<string>('uri'),
    }),
  })

  if (status === 'error') return null
  if (loading && entries.length === 0) return <p>Loading related stories…</p>

  return (
    <section aria-label="Related stories">
      {entries.map(entry => (
        <FroomleReco key={entry.item.id} entry={entry} asChild>
          <article><a href={entry.item.url}>{entry.item.title}</a></article>
        </FroomleReco>
      ))}
    </section>
  )
}
```

-   `status`, `loading`, and `error` describe the current request.
    
-   `experience`, `list`, and `response` describe the current successful result and are `null` while it is loading or has failed. `response` is the SDK result, not the unfiltered backend payload.
    
-   `items` contains the raw SDK recommendation items available for display. It does not contain original CMS cards. You can pass an item directly as FroomleReco reco={item} if you only render returned items.
    
-   A successful Froomle experience with no items does not fall back to `customerItems`. `exclusions`, `excludeItems`, and `autoExclusions` apply to the request; see [React exclusions](https://docs.froomle.com/froomle-doc-main/v2/js_lib/react.html#ExclusionsReact).
    

<a id="_usesmartsort"></a>

#### `useSmartSort`

Use `useSmartSort(…​)` when you already have the candidate items and want to change their order rather than fetch new items. See [Smart Sort with React](https://docs.froomle.com/froomle-doc-main/v2/js_lib/smart-sorting-reranking.html#SmartSortReact) for the candidate inputs, result fields, and a React example.

<a id="react-reco-entry"></a>

#### `useRecoEntry`

Use `useRecoEntry(…​)` for a single card that can show either an original CMS item or a Froomle recommendation. It returns one `FroomleRecoEntry` or `null` when there is no usable entry. This is a render value, not a promise-like handle.

```tsx
import { FroomleReco, useRecoEntry } from '@froomle/frontend-sdk/react'

type Article = { id: string; title: string; url: string }

export function FeaturedStory({ original }: { original: Article }) {
  const entry = useRecoEntry({
    list: 'featured_story',
    customerItem: { item: original, getId: article => article.id },
    mapRecommendationItem: (reco): Article => ({
      id: reco.Id,
      title: reco.get<string>('title'),
      url: reco.get<string>('uri'),
    }),
  })

  if (!entry) return null
  return (
    <FroomleReco entry={entry} asChild>
      <article><a href={entry.item.url}>{entry.item.title}</a></article>
    </FroomleReco>
  )
}
```

<a id="react-consent-refresh"></a>

#### What stays visible when consent is granted

If consent increases without changing identity, page, or query, `useRecoList(…​)` and `useRecoEntry(…​)` can keep displaying the previous cards while the SDK requests a fresh result. For a list, `loading` can be true while `entries` (or raw `items`) still contain the displayed cards. Use a loading placeholder only when there is nothing to display.

Those cards cannot send new impressions or clicks against the old request. Tracking resumes when `FroomleReco` registers a fresh result, and a click during the refresh is not replayed. Keep the existing components mounted and only forward the consent change with `setConsent(…​)`. Do not send compensating events.

This does not preserve old cards after consent withdrawal, a change of identity, page, or query, or a refresh that fails or selects no cards.

<a id="react-reco-tracking"></a>

#### `FroomleReco`

Pass either `entry` from a hook or `reco` (a handle or raw item returned by the hook), not both. Keep the SDK-returned object intact: copying it or constructing something with the same fields does not carry its tracking association. Use a stable React key for each list card, such as its item ID, not its array position or request ID.

By default, `FroomleReco` renders a `<div>`. Use `asChild` with one DOM element if the card itself must be the grid or flex child. If you pass a custom component, forward the props and ref to its actual DOM root so the SDK can register the card for automatic tracking:

```tsx
import { forwardRef } from 'react'
import type { ComponentPropsWithoutRef } from 'react'

export const ArticleRoot = forwardRef<HTMLElement, ComponentPropsWithoutRef<'article'>>(
  function ArticleRoot(props, ref) {
    return <article {...props} ref={ref} />
  }
)
```

`useReco()` reads the nearest `FroomleReco` context: the selected `entry.item`, the raw recommendation, or the handle passed as `reco`. It throws outside that wrapper. If your application renders the finished cards without `FroomleReco`, send [recommendation events](https://docs.froomle.com/froomle-doc-main/v2/js_lib/sdk-events.html#send-event) explicitly instead.

<a id="_froomleorder"></a>

#### `FroomleOrder`

Use `FroomleOrder` with `FroomleOrderItem` to order whole React sections by category instead of filling recommendation cards:

```tsx
import { FroomleOrder, FroomleOrderItem } from '@froomle/frontend-sdk/react'

export function TopicSections() {
  return (
    <FroomleOrder list="homepage_topics" category="categories">
      <FroomleOrderItem value="Sports"><section>Sports</section></FroomleOrderItem>
      <FroomleOrderItem value="World"><section>World</section></FroomleOrderItem>
    </FroomleOrder>
  )
}
```

<a id="_froomlecustomitem"></a>

#### `FroomleCustomItem`

Use `FroomleCustomItem` for an editorial item you want to add to SDK history. It renders its children without a DOM wrapper and registers the ID with `addHistories(…​)`; it does not fetch recommendations or register recommendation impressions and clicks.

```tsx
import { FroomleCustomItem } from '@froomle/frontend-sdk/react'

export function EditorsPick() {
  return (
    <FroomleCustomItem id="article-123">
      <article><a href="/news/article-123">Editor's pick</a></article>
    </FroomleCustomItem>
  )
}
```

<a id="_arcxp_fusion"></a>

### ArcXP / Fusion

In ArcXP / Fusion, use the following runtime model:

-   the `Output Type` is the server-rendered shell
    
-   the client-rendered / rehydrated React layer runs under `#fusion-app`
    

Recommended ArcXP integration:

-   Initialize page/app-level SDK state in the client-rendered React layer.
    
-   Mount `FroomleSdkInit` there.
    
-   Render recommendation UI with `useCreateReco` or `useRecoList`, together with `FroomleReco` / `useReco`, there.
    
-   Keep the `Output Type` limited to server-shell responsibilities.
    
-   If a page only needs automatic `page_visit` and no recommendations yet, still mount `FroomleSdkInit` on that page and set `setPageVisit(…​)`. No recommendation component is required.
    
-   If a detail page only needs automatic `detail_pageview` and no recommendations, still mount `FroomleSdkInit` on that page and set `setPageVisit(…​)`, `setContextItem(…​)`, and optional `setContextItemType(…​)`. No recommendation component is required for that page.
    
-   A homepage-only React integration does not automatically give destination article pages their own `detail_pageview`; the destination detail page still needs its own lightweight SDK bootstrap.
    

The following setters define page/app-level runtime state and are normally set once per page context, not once per recommendation block:

-   `setEnvironment(…​)`
    
-   `setPageVisit(…​)`
    
-   `setChannel(…​)`
    
-   `setSiteContext(…​)` for an optional analytics-context override
    
-   `setSubscriptionLevel(…​)`
    
-   `setConsent(…​)`
    
-   `setDeviceId(…​)`
    
-   `setUserId(…​)`
    
-   `setContextItem(…​)`
    
-   `setContextItemType(…​)`
    

If a page contains multiple recommendation blocks, set these values once for the current page context and render the blocks against that shared SDK state. If the page context changes during client-side navigation, update the page-level setters once for the new route/context.

ArcXP integration options:

| Path | Use when | Notes |
| --- | --- | --- |
| React bindings in the client-rendered layer under `#fusion-app` | Recommendations are part of the React app itself. | Preferred ArcXP integration. Use `@froomle/frontend-sdk/react`, mount `FroomleSdkInit` in the browser layer, and render one or more recommendation blocks from shared page-level SDK state. |
| Script-tag/static shell | The server renders placeholders that the script-tag SDK fills in the browser, without React rehydration. | Narrow exception only. Use this in the `Output Type` shell or in a feature explicitly marked `.static = true`. Do not use this for normal rehydrated ArcXP feature trees. |

> **TIP:**
> 
> Use [frontend-sdk-examples](https://bitbucket.org/froomle/frontend-sdk-examples) for runnable examples. The examples repo includes an ArcXP React example (`arcxp-native-react-example`) and a static-shell exception example (`arcxp-native-static-example`).

<a id="ExclusionsReact"></a>

## Exclusions in React

React hooks support `exclusions`, `excludeItems`, and `autoExclusions` request options. Render returned items through `FroomleReco` so automatic recommendation-item tracking still works.

Slot-based `useCreateReco(…​)`:

```tsx
const reco = useCreateReco({
  list: 'recommended_for_you',
  filters: [],
  autoExclusions: true
})

return (
  <FroomleReco reco={reco}>
    <ArticleCard />
  </FroomleReco>
)
```

List-based `useRecoList(…​)`:

```tsx
const { items } = useRecoList({
  list: 'recommended_for_you',
  limit: 4,
  list_size: 4,
  filters: [],
  autoExclusions: true
})

return items.map((item) => (
  <FroomleReco reco={item} key={item.Id}>
    <ArticleCard item={item} />
  </FroomleReco>
))
```

For React/CMS setups where the page already has visible article objects in memory, prefer `excludeItems` over DOM scanning. This is useful for ArcXP-style pages where the CMS composes the page from article objects and the recommendation lane should avoid articles already rendered above or elsewhere on the page:

```tsx
const { items } = useRecoList({
  list: 'recommended_for_you',
  limit: cmsListSize,
  list_size: cmsListSize,
  filters: [],
  excludeItems: {
    items: articlesAlreadyRenderedAbove,
    getId: (article) => article._id,
    itemType: 'article'
  }
})
```

`articlesAlreadyRenderedAbove` is not a Froomle-specific object shape. It is the caller-owned array of CMS/ArcXP items that are already rendered, or are known to be rendered, on the page. The SDK does not send those full objects to Froomle. It only calls `getId(…​)` and `getItemType(…​)` / `itemType` to build request-local exclusion entries.

If the CMS objects expose the ArcXP id through `_id`, use:

```tsx
const excludeItems = {
  items: articlesAlreadyRenderedAbove,
  getId: (article) => article._id,
  itemType: 'article'
}
```

If only IDs are available, pass the ID array directly:

```tsx
const alreadyRenderedArticleIds = [
  'JM43X5OXWJDSNDT2CGGDHWDUTY',
  'HTRDQNGS2ZANBMJUSB7E7KELDU'
]

const { items } = useRecoList({
  list: 'recommended_for_you',
  limit: cmsListSize,
  list_size: cmsListSize,
  excludeItems: {
    items: alreadyRenderedArticleIds,
    getId: (id) => id,
    itemType: 'article'
  }
})
```

This maps to `histories.exclude` entries like:

```json
{
  "id": "JM43X5OXWJDSNDT2CGGDHWDUTY",
  "item_type": "article",
  "reconsumable": false
}
```

When you already have the exact exclusion IDs and do not need an item adapter, passing `exclusions` directly is also valid:

```tsx
const { items } = useRecoList({
  list: 'recommended_for_you',
  limit: cmsListSize,
  list_size: cmsListSize,
  exclusions: alreadyRenderedArticleIds.map((id) => ({
    id,
    item_type: 'article'
  }))
})
```

`excludeItems` is only an adapter. The SDK maps it to request-level `histories.exclude` entries before sending the recommendation request. Use the `items` array to control scope: pass only items above the lane, all items in the surrounding matrix, or all known page items depending on the deduplication rule you want. In TypeScript, the item type is inferred from `excludeItems.items`, so `getId(…​)` and `getItemType(…​)` can read the CMS object shape directly.

Entry-based `useRecoEntry(…​)` for one request slot:

```tsx
const entry = useRecoEntry({
  list: 'recommended_for_you',
  excludeItems: {
    items: articlesAlreadyRenderedAbove,
    getId: (article) => article._id,
    itemType: 'article'
  }
})

return entry ? (
  <FroomleReco entry={entry}>
    <ArticleCard item={entry.item} />
  </FroomleReco>
) : null
```

`useReco(…​)` reads the current `FroomleReco` context and does not send a recommendation request by itself. Configure exclusions on the request-producing hook: `useCreateReco(…​)`, `useRecoList(…​)`, or `useRecoEntry(…​)`. See [the React single-entry example](https://docs.froomle.com/froomle-doc-main/v2/js_lib/react.html#react-reco-entry) for how to render a slot that can show an original card.
