src/platform/packages/shared/kbn-react-hooks/README.md
A utility package, @kbn/react-hooks, provides custom react hooks for simple abstractions.
Simplify handling boolean value with predefined handlers.
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>
);
}
Returns styles used for styling error text.
function App() {
const errorTextStyle = useErrorTextStyle();
return (
<div>
<EuiText css={errorTextStyle}>Error message</EuiText>
</div>
);
}
Wrapper around async function which is called on dependency change and can be aborted via abort controller.
const { error, loading, value, refresh } = useAbortableAsync(
({ signal }) => {
return fetch(url, { signal })
},
[url],
{ onError: myErrorHandler }
);
Hook managing an abort controller instance that aborts when it goes out of scope.
const { signal, abort, refresh } = useAbortController();
// ...
// Will be aborted when the component unmounts
await fetch(url, { signal })
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.
// 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,
});
Hook for managing text truncation with expand/collapse functionality. Provides controlled truncation of long text content with customizable length.
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>