Develop ultra fast with Prismane 🎉

useSorting

useSorting hook provides a simple way of sorting big chunks of data by key and direction.

Import

import { useSorting } from "@prismane/core/hooks";

Usage

function Demo() {
  const items = [
    { name: "Apple", quantity: 10 },
    { name: "Banana", quantity: 5 },
    { name: "Cherry", quantity: 15 },
    { name: "Date", quantity: 8 },
  ];

  const { sorted, key, direction, setKey, toggleDirection } = useSorting(
    items,
    "name"
  );

  return (
    <Stack as={Center}>
      <Button onClick={() => setKey("name")}>Sort by Name</Button>
      <Button onClick={() => setKey("quantity")}>Sort by Quantity</Button>
      <Button onClick={toggleDirection}>Toggle Order</Button>
      <Stack mt={fr(6)}>
        {sorted.map((item, index) => (
          <Text key={index}>
            {item.name} - {item.quantity}
          </Text>
        ))}
      </Stack>
      <Text>
        Sorting by: <Text as="strong">{key}</Text> (Order:{" "}
        <Text as="strong">{direction}</Text>)
      </Text>
    </Stack>
  );
}

API

Parameters

NameTypeDescriptionDefault
dataany[]The data that will be tracked.-
initialKeystring / nullThe key by which the data will be sorted.null
initialDirection'asc' / 'desc'The direction by which the data will be sorted.'asc'
optionsuseSortingOptionsThe options of the hook.{ resetDirectionOnKeyChange: true }
type useSortingOptions = {
  resetDirectionOnKeyChange?: boolean;
};

Return Value

NameTypeDescription
sortedany[]The sorted data.
keystringThe current key by which the hook is sorting.
direction'asc' / 'desc'The current direction by which the hook is sorting.
setKey(key: string) => voidThe function that sets the new key by which the hook will sort.
setDirection(direction: 'asc' / 'desc') => voidThe function that sets the new direction by which the hook will sort.
toggleDirection() => voidThe function that toggles the direction by which the hook will sort.