import { useEventListener } from "@dreamy-ui/react";
useEventListener
is a hook that allows you to listen to events on the target.
Count: 0
export function UseEventListener() {
const [count, setCount] = useState(() =>
typeof window === "undefined" ? 0 : Number(localStorage.getItem("count")) || 0
);
useEventListener("click", () => {
setCount((prev) => {
const newCount = prev + 1;
localStorage.setItem("count", newCount.toString());
return newCount;
});
});
return <Text>Count: {count}</Text>;
}
useEventListener
also accepts a target and an options object. Target can be a function that returns a DOM element, making it compatible with SSR.
useEventListener("click", () => {}, () => document, { fireOnMount: true });
Example below will toggle color mode on cmd + i
or ctrl + i
.
import { useColorMode, useEventListener, getActionKeyCode } from "@dreamy-ui/react";
export function ToggleColorMode() {
const { toggleColorMode } = useColorMode();
useEventListener("keydown", (event) => {
if (event.key === "i" && event[getActionKeyCode()] && !event.shiftKey) {
toggleColorMode();
}
});
}