Skip to content

Utility Functions

Collection of helpful utility functions.

import {
  useInterval,
  lowercase,
  formatPrice,
  cn,
  capitalize,
  useRouteData,
  useDocumentScrollThrottled,
} from "~/lib/utils";
  • useInterval: This function is a custom React Hook designed to execute a callback function at specified intervals. It accepts two parameters: callback, representing the function to execute, and delay, indicating the time between each execution in milliseconds. It returns a cancel function to stop the interval.

  • lowercase: A function that converts a given string to lowercase. It's commonly used for standardizing text inputs or ensuring uniformity in data processing.

  • formatPrice: This function converts a numerical value into a formatted price string using USD currency format. It utilizes the Intl.NumberFormat API to ensure accurate formatting based on the user's locale.

  • cn: A utility function that merges classNames with Tailwind CSS classes and returns the combined string. It simplifies the process of dynamically composing class names in React components, leading to cleaner and more maintainable code. This function is essential for integrating Tailwind CSS with shadcn components.

  • capitalize: This function capitalizes the first letter of a given string. It's often used to enhance the visual presentation of text inputs or to ensure consistency in text display.

  • useRouteData: This function is a custom React Hook used to retrieve data specific to a route. It takes a routePathname parameter, representing the pathname of the route to fetch data for. It internally uses useMatches from Remix's @remix-run/react package to get route matches and filters the matches based on the provided routePathname. The function returns the route data for the given pathname, or undefined if no data is found for that route. This function is particularly useful for accessing route-specific data within React components.

  • useDocumentScrollThrottled: This hook is designed to execute a callback function whenever the document is scrolled. It uses lodash's _.throttle function to limit the frequency of callback invocations to at most once every 250 milliseconds, preventing excessive calls and improving performance. The callback function receives information about the scroll position, including the previous and current scroll top positions. This hook is useful for implementing scroll-related behaviors or effects in React components.