# useSettings

>[!WARNING]
>Legacy Pattern > This hook has become significantly complex and "heavy" due to the need to support legacy stripes-smart-components patterns while managing dynamic context injection.
> It is possible that this pattern will be significantly reworked in future versions to separate data-fetching logic from UI component generation in a more modular way.

A comprehensive hook that manages the retrieval and configuration of settings data for one or multiple sections. It orchestrates multiple queries with `react-query`, constructs dynamic pages for each settings section, and returns a pre-configured `SettingsComponent` for rendering the settings UI.

## Overview

`useSettings` serves several purposes:

- **Multi-Section Querying:**  
  It supports both single and multiple settings sections. Depending on the provided props, it dynamically generates query parameters and uses `useQueries` to fetch data for each section.

- **Dynamic Page Generation:**  
  When queries return data, it extracts unique section names to create dynamic pages. Each page includes a route, localized label, and a component that wraps a `SettingPage` in a `SettingPagePane`.

- **Context and Configuration:**  
  The hook creates a `SettingsContextProvider` to pass down configuration details (like API endpoints and internationalization keys) to its children. This ensures that each section or page has the necessary context for rendering.

- **Final Settings Component:**  
  It returns a `SettingsComponent` that wraps the list of pages or sections using the `Settings` component from `@folio/stripes/smart-components`. This component can then be directly rendered in the application.

## Basic Usage

```jsx
const SettingsContainer = () => {
  const {
    isLoading,
    SettingsComponent,
    pageList,
    sections,
    SettingsContextProvider,
  } = useSettings({
    sectionName: 'general',
    settingEndpoint: '/settings',
    refdataEndpoint: '/refdata',
    // Other optional props for customization...
  });

  if (isLoading) return <div>Loading settings...</div>;

  return <SettingsComponent />;
};
```

## Parameters

`useSettings` accepts an optional settings props object (`settingsProps`) that may include the following properties:

| Name                    | Type      | Description                                                                                                                                                                                                                                | Required |
|-------------------------|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|
| `allowGlobalEdit`       | `boolean` | Global flag to enable or disable editing of settings. Defaults to `true`.                                                                                                                                                                  | ✕        |
| `contextPerPage`        | `boolean` | If `true`, wraps every individual page component in a Context Provider. Set to `false` if encountering redraw issues with SASQ components. Defaults to `true`, see "Performance & Redraws" section below for more information.             | ✕        |
| `dynamicPageExclusions` | `array`   | Array of section names to be excluded from dynamic page generation.                                                                                                                                                                        | ✕        |
| `intlKey`               | `string`  | Base internationalization key for resolving labels.                                                                                                                                                                                        | ✕        |
| `intlNS`                | `string`  | Internationalization namespace.                                                                                                                                                                                                            | ✕        |
| `labelOverrides`        | `object`  | Custom label overrides for specific settings keys.                                                                                                                                                                                         | ✕        |
| `pages`                 | `array`   | If provided, acts as a passthrough configuration for either sections or standalone pages, disabling query execution.                                                                                                                       | ✕        |
| `persistentPages`       | `array`   | Array of pages that persist regardless of dynamic query results.                                                                                                                                                                           | ✕        |
| `preventQueries`        | `boolean` | Flag to disable querying if settings data is provided externally.                                                                                                                                                                          | ✕        |
| `refdataEndpoint`       | `string`  | The API endpoint to retrieve reference data for settings.                                                                                                                                                                                  | ✕        |
| `renderSingleSection`   | `boolean` | When only one section is available, determines if it should be rendered as a single section with its own label.                                                                                                                            | ✕        |
| `sectionPermission`     | `string`  | Permission string that, if provided, restricts the rendering of a section unless the current user has the specified permission.                                                                                                            | ✕        |
| `sectionRoute`          | `string`  | Base route path to be used when constructing dynamic page routes for settings sections.                                                                                                                                                    | ✕        |
| `sections`              | `array`   | Array of section configuration objects. Each object can override or extend the global settings props for that specific section. This means that the shape here matches more or less the shape for the props of `useSettings` itself.       | ✕        |
| `settingEndpoint`       | `string`  | The base URL endpoint for fetching and updating settings.                                                                                                                                                                                  | ✕        |
| `templateEndpoint`      | `string`  | The endpoint for retrieving settings templates (if applicable).                                                                                                                                                                            | ✕        |
| `render`                | `func`    | A custom render function for rendering individual setting fields. This function is passed down to the underlying settings components for specialized display logic. See `EditableSettingsList` for more information on how render is used. | ✕        |

## Returns

The hook returns an object containing:

- **`isLoading`** (`boolean`):  
  Indicates if any of the settings queries are still loading.

- **`pageList`** (`array`):  
  An array of pages to be rendered by the `Settings` component. This is the final list of pages for a single section, if applicable.

- **`sections`** (`array`):  
  An array of fully configured sections. Each section includes its own `SettingsContextProvider`, dynamic pages, and additional configuration data.

- **`SettingsComponent`** (`React Component`):  
  A component pre-configured with the pages and sections that renders the settings UI. This component wraps the settings in the required `Settings` component from `@folio/stripes/smart-components`.

- **`SettingsContextProvider`** (`React Component`):  
  A context provider component for settings configuration. If only one section is available, it is provided directly; otherwise, it defaults to a pass-through provider.

## Performance and redraws
Because SettingsComponent is generated within the hook, its function reference changes whenever the underlying settings data (like pageList or sections) updates.

In some complex scenarios (e.g., using SearchAndSortQuery inside a settings page), this can cause the entire settings pane to unmount and remount (a "redraw"). If you experience lost input focus or flickering, instead of using the returned SettingsComponent, manually render the Settings component using the pageList or sections provided by the hook:

```javascript
import { Settings } from '@k-int/stripes-kint-components';

const { isLoading, pageList, sections } = useSettings({
  contextPerPage: false, // This should be turned off for this pattern
  ...restOfConfig
});

if (isLoading) return null;

return (
  <Settings
    {...props}
    pages={pageList}
    sections={sections}
    paneTitle={<FormattedMessage id="my-app.settings.title" />}
  />
);
```