useSelect
Manages a selection state from a list of options with helpers.
About
Select values from a list easily. List selection hook for react.
Examples
Basic usage
import { useSelect } from "rooks";
const list = [
{
heading: "Awesome",
content: "Great, tell me about it!",
},
{
heading: "I don't know",
content: "That's okay.",
},
{
heading: "Worst",
content: "The day is young.",
},
];
export default function App() {
const { index, setIndex, item } = useSelect(list, 0);
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: "20px",
}}
>
<h1>Rooks: useSelect Example</h1>
<h3>How're you feeling today?</h3>
{list.map((listItem, listItemIndex) => (
<button
key={listItemIndex}
style={{
background: index === listItemIndex ? "Teal" : "inherit",
}}
onClick={() => setIndex(listItemIndex)}
>
{listItem.heading}
</button>
))}
<p>{item.content}</p>
</div>
);
}Keep the selected item in sync with external controls
import { useSelect } from "rooks";
const filters = ["all", "open", "done"];
export default function FilterPicker() {
const { index, item, setIndex, setItem } = useSelect(filters, 0);
return (
<div>
<p>
Selected filter: {item} (index {index})
</p>
<button onClick={() => setIndex(1)}>Open</button>
<button onClick={() => setItem("done")}>Done</button>
</div>
);
}Parameters
| Argument | Type | Description | Default value |
|---|---|---|---|
| list | Array | List of items for which the selection is used | undefined |
| initialIndex | number | Initially selected index | 0 |
Returned Object
| Returned object attributes | Type | Description |
|---|---|---|
| index | int | Index of currently selected index |
| item | any | Currently selected item |
| setIndex | function | Update selected index |
| setItem | function | Update selected item |
Return value
Returns { index, item, setIndex, setItem }. item is list[index]; the public type is T, but an out-of-range index produces undefined at runtime. setItem(value) selects the first strict-equality match and sets the index to -1 when the value is absent.
Behavior and lifecycle
The selected index is initialized once and is not automatically reset when list or initialIndex changes. setItem is recreated when the list reference changes. The hook performs no bounds validation, warnings, effects, or cleanup.
Compatibility and accessibility
The hook is SSR-safe. Prefer a native <select>, radio group, or another control with explicit selected state; validate indices before using them to render user-facing content.