Back to Kibana

@kbn/react-hooks

src/platform/packages/shared/kbn-react-hooks/README.md

9.4.02.7 KB
Original Source

@kbn/react-hooks

A utility package, @kbn/react-hooks, provides custom react hooks for simple abstractions.

Custom Hooks

useBoolean

Simplify handling boolean value with predefined handlers.

tsx
function App() {
  const [value, { on, off, toggle }] = useBoolean();

  return (
    <div>
      <EuiText>
        The current value is <strong>{value.toString().toUpperCase()}</strong>
      </EuiText>
      <EuiFlexGroup>
        <EuiButton onClick={on}>On</EuiButton>
        <EuiButton onClick={off}>Off</EuiButton>
        <EuiButton onClick={toggle}>Toggle</EuiButton>
      </EuiFlexGroup>
    </div>
  );
}

useErrorTextStyle

Returns styles used for styling error text.

tsx
function App() {
  const errorTextStyle = useErrorTextStyle();

  return (
    <div>
      <EuiText css={errorTextStyle}>Error message</EuiText>
    </div>
  );
}

useAbortableAsync

Wrapper around async function which is called on dependency change and can be aborted via abort controller.

tsx
  const { error, loading, value, refresh } = useAbortableAsync(
    ({ signal }) => {
      return fetch(url, { signal })
    },
    [url],
    { onError: myErrorHandler }
  );

useAbortController

Hook managing an abort controller instance that aborts when it goes out of scope.

tsx
  const { signal, abort, refresh } = useAbortController();

  // ...

  // Will be aborted when the component unmounts
  await fetch(url, { signal })

useDebouncedValue

Returns a debounced version of the provided value. The returned value only updates after the specified wait period has elapsed since the last change. Accepts an optional compare function to customise equality checks.

tsx
// Basic usage
const debouncedQuery = useDebouncedValue(query, 300);

// With a custom comparator for object values
const debouncedFilters = useDebouncedValue(filters, 500, {
  compare: (a, b) => a.id === b.id,
});

useTruncateText

Hook for managing text truncation with expand/collapse functionality. Provides controlled truncation of long text content with customizable length.

tsx
const { displayText, isExpanded, toggleExpanded, shouldTruncate } = useTruncateText(
  longContent,
  150,          // Max length before truncation (default: 500)
  100           // Optional: Max characters to show when truncated
);

<EuiText>
  {displayText}
  {shouldTruncate && (
    <EuiLink onClick={toggleExpanded}>
      {isExpanded ? 'Show less' : 'Show more'}
    </EuiLink>
  )}
</EuiText>