Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/lib/hooks/use-boolean.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"use client";

import { useCallback, useState } from "react";

/**
* Reusable boolean toggle hook for open/close, active/inactive states (#291).
*
* Returns a tuple of the boolean value and three memoized control functions:
* `setTrue`, `setFalse`, and `toggle`.
*/
export function useBoolean(
initialValue = false,
): readonly [boolean, () => void, () => void, () => void] {
const [value, setValue] = useState(initialValue);

const setTrue = useCallback(() => setValue(true), []);
const setFalse = useCallback(() => setValue(false), []);
const toggle = useCallback(() => setValue((prev) => !prev), []);

return [value, setTrue, setFalse, toggle];
}
33 changes: 33 additions & 0 deletions src/lib/hooks/use-click-outside.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"use client";

import { useEffect } from "react";
import type { RefObject } from "react";

type ClickOutsideRef = RefObject<HTMLElement | null>;

/**
* Trigger a callback when a click occurs outside the given ref(s) (#289).
*
* Accepts a single ref or an array of refs (e.g. a dropdown trigger and its
* menu), listens on `mousedown`, and removes the listener on unmount.
*/
export function useClickOutside(
refs: ClickOutsideRef | ClickOutsideRef[],
handler: (event: MouseEvent) => void,
) {
useEffect(() => {
const clickOutsideRefs = Array.isArray(refs) ? refs : [refs];

const onMouseDown = (event: MouseEvent) => {
const target = event.target as Node;
const isOutside = clickOutsideRefs.every(
(ref) => !ref.current || !ref.current.contains(target),
);

if (isOutside) handler(event);
};

document.addEventListener("mousedown", onMouseDown);
return () => document.removeEventListener("mousedown", onMouseDown);
}, [refs, handler]);
}
19 changes: 19 additions & 0 deletions src/lib/hooks/use-previous.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"use client";

import { useEffect, useRef } from "react";

/**
* Access the previous value of a state or prop (#290).
*
* Returns `undefined` on the first render and the value from the previous
* render on subsequent renders, updating after the component re-renders.
*/
export function usePrevious<T>(value: T): T | undefined {
const previousRef = useRef<T | undefined>(undefined);

useEffect(() => {
previousRef.current = value;
}, [value]);

return previousRef.current;
}