No! 👎<\/span>}\
<\/button>\
<\/div>\
);\
}
```
--------------------------------
### Installing Rooks Library via npm
Source: https://github.com/imbhargav5/rooks/blob/main/README.md
This command installs the Rooks library, a collection of React hooks, as a dependency in your project using npm. The `-s` flag is a shorthand for `--save`, which adds the package to the `dependencies` section of your `package.json` file.
```Shell
npm i -s rooks
```
--------------------------------
### Basic Usage of useSetState Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useSetState.md
This example demonstrates the most basic usage of the `useSetState` hook. It imports the hook from the 'rooks' library and calls it within a functional React component. While this specific example doesn't show state manipulation, it illustrates the minimal setup required to integrate the hook into an application.
```jsx
import { useSetState } from "rooks";
export default function App() {
useSetState();
return null;
}
```
--------------------------------
### Using useDidMount Hook in a React Component
Source: https://github.com/imbhargav5/rooks/blob/main/packages/rooks/README.md
This example illustrates the practical application of the 'useDidMount' hook within a functional React component. The callback function provided to 'useDidMount' will execute exactly once, immediately after the component has successfully mounted to the DOM.
```JSX
function App() {
useDidMount(() => {
alert("mounted");
});
return (
Hello CodeSandbox
Start editing to see some magic happen!
);
}
```
--------------------------------
### Adding Changeset Information - Yarn Command
Source: https://github.com/imbhargav5/rooks/blob/main/CONTRIBUTING.md
This command guides the user through adding changeset information, which is crucial for tracking new features or bug fixes for release management. It helps in bumping package versions appropriately and generating release notes.
```shell
yarn changeset
```
--------------------------------
### Basic Usage of useVibrate Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useVibrate.mdx
This example demonstrates the basic usage of the `useVibrate` hook. It imports the hook from 'rooks' and calls it within a functional React component, enabling vibration functionality.
```TypeScript
import {useVibrate} from "rooks"
export default function App() {
useVibrate();
return null
}
```
--------------------------------
### Basic Usage of useOnHoverRef Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useOnHoverRef.mdx
This example demonstrates the most basic usage of the `useOnHoverRef` hook within a React functional component. It imports the hook from the 'rooks' library and calls it inside the `App` component, showing how to integrate it without any specific hover logic, serving as a minimal setup.
```TypeScript
import {useOnHoverRef} from "rooks"
export default function App() {
useOnHoverRef();
return null
}
```
--------------------------------
### Using useMediaMatch Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useMediaMatch.mdx
This example demonstrates how to use the `useMediaMatch` hook from the `rooks` library to dynamically check if the screen width is less than or equal to 600px. It renders 'narrow' or 'wide' based on the media query match, providing a responsive UI.
```jsx
import "./styles.css";
import { useMediaMatch } from "rooks";
function App() {
const Component = useMediaMatch("(max-width: 600px)");
return (
Rooks : useMediaMatch example
Your screen is {Component ? "narrow" : "wide"}
);
}
export default App;
```
--------------------------------
### Initializing useInput Hook in React (Simple Example)
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useInput.mdx
This snippet demonstrates the basic usage of the `useInput` hook from the 'rooks' library. It initializes an input field with a default value 'hello' and dynamically displays its current value, providing a straightforward way to manage input state.
```jsx
import { useInput } from "rooks";
export default function App() {
const myInput = useInput("hello");
return (
);
}
```
--------------------------------
### Basic Initialization of useUndoRedoState Hook in TSX
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useUndoRedoState.md
This snippet demonstrates the most basic usage of the useUndoRedoState hook within a React functional component. It imports the hook from the 'rooks' library and calls it without any arguments, serving as a minimal example of its integration.
```TSX
import {useUndoRedoState} from "rooks"
export default function App() {
useUndoRedoState();
return null
}
```
--------------------------------
### Setting Conditional Interval with useIntervalWhen (Basic) - React JSX
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useIntervalWhen.md
This example demonstrates the basic usage of the `useIntervalWhen` hook. It sets up an interval that increments a state variable `value` every second, but only when the `when` state variable is true. The interval starts only after the 'Start interval' button is clicked.
```jsx
import { useIntervalWhen } from "rooks";
import { useState } from "react";
function App() {
const [value, setValue] = useState(0);
const [when, setWhen] = useState(false);
useIntervalWhen(
() => {
setValue(value + 1);
},
1000, // run callback every 1 second
when // start the timer when it's true
);
return (
Rooks: useIntervalWhen example
Value: {value}
setWhen(true)}> Start interval
);
}
export default App;
```
--------------------------------
### Basic Usage of useWindowSize Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useWindowSize.mdx
This example demonstrates how to integrate and use the `useWindowSize` hook from the 'rooks' library within a React functional component. It shows how to destructure the returned object to access `innerWidth`, `innerHeight`, `outerHeight`, and `outerWidth` and display them dynamically in the UI.
```JSX
import "./styles.css";
import { useWindowSize } from "rooks";
function App() {
const { innerWidth, innerHeight, outerHeight, outerWidth } = useWindowSize();
return (
Rooks: useWindowSize Example
innerHeight -
{innerHeight}
innerWidth -
{innerWidth}
outerHeight -
{outerHeight}
outerWidth -
{outerWidth}
);
}
export default App;
```
--------------------------------
### Basic Integration of a Rooks Utility/Hook (TypeScript)
Source: https://github.com/imbhargav5/rooks/blob/main/template/README.md
This snippet illustrates the fundamental way to import and utilize a Rooks utility or hook (represented by "%name%") within a React functional component. It shows the import statement and a direct call to the utility within the component's body, assuming it's a hook or a function that can be invoked without arguments for this basic example.
```TypeScript
import {%name%} from "rooks"
export default function App() {
%name%();
return null
}
```
--------------------------------
### Basic Usage of useIsDroppingFiles Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useIsDroppingFiles.md
This example demonstrates the basic integration of the `useIsDroppingFiles` hook from the `rooks` library into a React functional component. The hook is called directly within the `App` component, providing a mechanism to track file drop events across the application. It requires the `rooks` package as a dependency.
```tsx
import { useIsDroppingFiles } from "rooks";
export default function App() {
useIsDroppingFiles();
return null;
}
```
--------------------------------
### Basic Usage of useTimeoutWhen Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useTimeoutWhen.mdx
This example demonstrates the basic usage of the `useTimeoutWhen` hook within a React functional component. It uses a state variable `start` to control a button's disabled state. Clicking the button sets `start` to `true`, which triggers the `useTimeoutWhen` hook. After a 2-second delay, the hook's callback sets `start` back to `false`, re-enabling the button.
```jsx
import "./styles.css";
import { useTimeoutWhen } from "rooks";
import { useState } from "react";
function App() {
const [start, setStart] = useState(false);
useTimeoutWhen(() => setStart(false), 2000, start);
return (
<>
Rooks: useTimeoutWhen example
Click the button below to disable it for 2 seconds
setStart(true)} disabled={start}>
Start timeout
>
);
}
export default App;
```
--------------------------------
### Handling Vowel Keydown Events with useKeyRef (JSX)
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useKeyRef.mdx
This example demonstrates the basic usage of `useKeyRef` to listen for specific keydown events on an input element. It attaches a ref to the input, and when any of the specified vowel keys are pressed, a callback function logs a message to the console.
```jsx
import { useKeyRef } from "rooks";
export default function App() {
function vowelsEntered(e) {
console.log("[Demo 1] You typed a vowel");
}
// window is the target
const inputRef = useKeyRef(["a", "e", "i", "o", "u"], vowelsEntered);
return (
<>
Press a,e,i,o,u in the input to trigger a console.log statement
>
);
}
```
--------------------------------
### Implementing useKeys Hook for Multiple Key Combinations in React
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useKeys.md
This example demonstrates how to use the `useKeys` hook to trigger callbacks when specific key combinations are pressed. It shows two instances: one for 'ControlLeft + S' on the document, and another for 'M + R' on an input field, illustrating the `target` and `when` options. It also includes state management for event activation and callback count.
```JSX
import * as React from "react";
import { useKeys } from "rooks";
export default function App() {
const containerRef = React.useRef(document);
const inputRef = React.useRef(null);
const [isEventActive, setIsEventActive] = React.useState(true);
const [firstCallbackCallCount, setFirstCallbackCallCount] = React.useState(0);
useKeys(
["ControlLeft", "KeyS"],
() => {
alert("you presses ctrlLeft + s");
setFirstCallbackCallCount(curr => curr + 1);
},
{
target: containerRef,
when: isEventActive,
preventLostKeyup: true,
}
);
useKeys(
["m", "r"],
event => {
// event.stopPropagation();
console.log("here you go m and r");
},
{
when: isEventActive,
target: inputRef,
}
);
return (
Callback Run Count:
{firstCallbackCallCount}
Is events enabled ? ==> {isEventActive ? "Yes" : "No"}
Press CtrlLeft + s to see update in count
{
setIsEventActive(!isEventActive);
}}
>
Toggle event enabled
);
}
```
--------------------------------
### Initializing useUndoRedoState Hook in TypeScript
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useUndoRedoState.mdx
This snippet demonstrates the basic initialization of the `useUndoRedoState` hook from the 'rooks' library within a React functional component. It shows how to import and call the hook without any specific state management, serving as a minimal example of its integration.
```tsx
import {useUndoRedoState} from "rooks"
export default function App() {
useUndoRedoState();
return null
}
```
--------------------------------
### Basic Usage of useDebounceFn in React (TypeScript)
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useDebounceFn.md
This snippet illustrates the fundamental way to integrate the `useDebounceFn` hook into a React functional component. It shows the necessary import statement from the 'rooks' library and a simple invocation of the hook within the `App` component, serving as a minimal working example.
```TypeScript
import {useDebounceFn} from "rooks"
export default function App() {
useDebounceFn();
return null
}
```
--------------------------------
### Basic Usage of useResizeObserverRef Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useResizeObserverRef.mdx
This example demonstrates the fundamental application of the `useResizeObserverRef` hook. It attaches a ref to a resizable div, and a callback function is executed to increment a counter every time the div's dimensions change. The example also includes buttons to dynamically adjust the position of the parent container, showcasing how the hook responds to layout shifts.
```jsx
import { useState } from "react";
import { useResizeObserverRef } from "rooks";
export default function App() {
const [resizeCount, setResizeCount] = useState(0);
const incrementResizeCount = () => {
return setResizeCount(resizeCount + 1);
};
const [myRef] = useResizeObserverRef(incrementResizeCount);
const [XOffset, setXOffset] = useState(0);
const [YOffset, setYOffset] = useState(300);
return (
<>
Resize this div as you see fit. To demonstrate that it also updates
on child dom nodes resize
Bounds
setXOffset(XOffset - 5)}> Move Left
setXOffset(XOffset + 5)}> Move Right
setYOffset(YOffset - 5)}> Move Up
setYOffset(YOffset + 5)}> Move Down
Resize count: {resizeCount}
>
);
}
```
--------------------------------
### Basic Usage of usePromise Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/usePromise.md
This example demonstrates the basic integration of the `usePromise` hook into a React functional component. It imports the hook from 'rooks' and calls it within the `App` component, returning `null` as a placeholder.
```tsx
import {usePromise} from "rooks"
export default function App() {
usePromise();
return null
}
```
--------------------------------
### Using useIntervalWhen Hook for Conditional Intervals - Immediate Callback (JSX)
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useIntervalWhen.mdx
This example illustrates how to use the `useIntervalWhen` hook to fire the callback function immediately when the condition becomes true, without waiting for the first interval duration. It increments a state variable `value` every second, starting instantly when the `when` state is true.
```jsx
import { useIntervalWhen } from "rooks";
import { useState } from "react";
function App() {
const [value, setValue] = useState(0);
const [when, setWhen] = useState(false);
useIntervalWhen(
() => {
setValue(value + 1);
},
1000, // run callback every 1 second
when, // start the timer when it's true
true // no need to wait for the first interval
);
return (
Rooks: useIntervalWhen example
Notice how the first increment is instantly after interval is enabled.
If n intervals run, the callback fires n+1 times.
Value: {value}
setWhen(true)}> Start interval
);
}
export default App;
```
--------------------------------
### Handling Basic Keydown Events with useKey (JSX)
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useKey.md
This example demonstrates the basic usage of the `useKey` hook to listen for keydown events. It shows how to attach listeners to the global window object for the 'Enter' key and to a specific input element for both lowercase and uppercase vowels. The `target` option allows specifying the DOM element to listen on.
```jsx
import React, { useRef, useState } from "react";
import "./styles.css";
import { useDebounce, useKey, useThrottle, useTimeoutWhen } from "rooks";
export default function App() {
const inputRef = useRef();
function windowEnter(e) {
console.log("[Demo 1] Enter key was pressed on window");
}
function vowelsEntered(e) {
console.log("[Demo 1] You typed a vowel");
}
function capitalVowelsEntered(e) {
console.log("[Demo 1] You typed a capital vowel");
}
// window is the target
useKey(["Enter"], windowEnter);
useKey(["a", "e", "i", "o", "u"], vowelsEntered, {
target: inputRef,
});
useKey(["A", "E", "I", "O", "U"], capitalVowelsEntered, {
target: inputRef,
});
return (
<>
Press enter anywhere to trigger a console.log statement
Press a,e,i,o,u in the input to trigger a console.log statement
Press A,E,I,O,U in the input to trigger a different log statement
>
);
}
```
--------------------------------
### Initializing useSpeech Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useSpeech.mdx
This example demonstrates the basic initialization of the `useSpeech` hook within a React functional component. It imports the hook from the 'rooks' library and calls it, returning `null` as the component's render output, indicating it's primarily for side effects.
```TypeScript
import {useSpeech} from "rooks"
export default function App() {
useSpeech();
return null
}
```
--------------------------------
### Basic Usage of useFreshCallback in TypeScript React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useFreshCallback.mdx
This example demonstrates the basic import and usage of the `useFreshCallback` hook within a React functional component. It shows how to include the hook in an application, although it doesn't illustrate a specific problem it solves.
```tsx
import {useFreshCallback} from "rooks"
export default function App() {
useFreshCallback();
return null
}
```
--------------------------------
### Basic Usage of useDeepCompareEffect Hook in TypeScript
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useDeepCompareEffect.mdx
This example demonstrates the basic usage of the `useDeepCompareEffect` hook from the 'rooks' library. It imports the hook and calls it within a functional component, illustrating its direct application without specific dependencies shown in this minimal example. This hook is useful when you need to trigger an effect only when the deep equality of its dependencies changes.
```TypeScript
import {useDeepCompareEffect} from "rooks"
export default function App() {
useDeepCompareEffect();
return null
}
```
--------------------------------
### Initializing File Drop with useFileDropRef Hook in TypeScript
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useFileDropRef.md
This example demonstrates how to integrate the `useFileDropRef` hook from the 'rooks' library into a React component. The hook simplifies the process of handling file drops on an element, making it easy to add drag-and-drop file upload functionality. It requires the 'rooks' library as a dependency.
```TypeScript
import { useFileDropRef } from "rooks";
export default function App() {
useFileDropRef();
return null;
}
```
--------------------------------
### Getting Geolocation in a React Component
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useGeolocation.mdx
This snippet demonstrates the basic usage of the `useGeolocation` hook to fetch and display a user's geolocation data immediately when the component mounts. It imports the hook and uses it to get a `geoObj` which is then stringified and rendered in a paragraph.
```jsx
import { useGeolocation } from "rooks";
import React from "react";
import { useState } from "react";
function App() {
const geoObj = useGeolocation();
return (
Rooks : useGeolocation Example
{geoObj && JSON.stringify(geoObj)}
);
}
export default App;
```
--------------------------------
### Setting Conditional Interval with useIntervalWhen (Immediate Start) - React JSX
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useIntervalWhen.md
This example shows how to use the `useIntervalWhen` hook to immediately invoke the callback function when the `when` condition becomes true, without waiting for the first interval duration to pass. It increments a state variable `value` every second, with the first increment happening instantly upon activation.
```jsx
import { useIntervalWhen } from "rooks";
import { useState } from "react";
function App() {
const [value, setValue] = useState(0);
const [when, setWhen] = useState(false);
useIntervalWhen(
() => {
setValue(value + 1);
},
1000, // run callback every 1 second
when, // start the timer when it's true
true // no need to wait for the first interval
);
return (
Rooks: useIntervalWhen example
Notice how the first increment is instantly after interval is enabled.
If n intervals run, the callback fires n+1 times.
Value: {value}
setWhen(true)}> Start interval
);
}
export default App;
```
--------------------------------
### Basic useToggle Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useToggle.md
This example demonstrates the fundamental usage of the `useToggle` hook without an initial value, defaulting to `false`. It shows how to toggle a boolean state and update the UI accordingly when a button is clicked, displaying 'Yes!' or 'No!' based on the state.
```jsx
import \"./styles.css\";\
import { useToggle } from \"rooks\";\
\
export default function App() {\
const [state, toggle] = useToggle();\
\
return (\
\
Rooks: useToggle Example <\/h1>\
<\/br>\
\
{state ? Yes! 👍<\/span> : No! 👎<\/span>}\
<\/button>\
<\/div>\
);\
}
```
--------------------------------
### Monitoring Online Status with useOnline Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useOnline.md
This example demonstrates how to use the `useOnline` hook from the 'rooks' library to detect and display the current online/offline status within a React component. It imports the hook, calls it to get the `online` boolean, and then renders a message indicating the status. The hook returns a boolean value representing the user's online status.
```JSX
import "./styles.css";
import { useOnline } from "rooks";
function App() {
const online = useOnline();
console.log("I'm online");
return (
Rooks: useOnline example
Status:You are {online ? "Online" : "Offline"}
);
}
export default App;
```
--------------------------------
### Handling Keyboard Events with useKey in React (Basic)
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useKey.mdx
This example demonstrates the basic usage of the `useKey` hook to listen for keyboard events. It shows how to attach event listeners to the window for a global 'Enter' key press and to a specific input element for vowel key presses (both lowercase and uppercase), logging different messages to the console based on the key and target.
```jsx
import React, { useRef, useState } from "react";
import "./styles.css";
import { useDebounce, useKey, useThrottle, useTimeoutWhen } from "rooks";
export default function App() {
const inputRef = useRef();
function windowEnter(e) {
console.log("[Demo 1] Enter key was pressed on window");
}
function vowelsEntered(e) {
console.log("[Demo 1] You typed a vowel");
}
function capitalVowelsEntered(e) {
console.log("[Demo 1] You typed a capital vowel");
}
// window is the target
useKey(["Enter"], windowEnter);
useKey(["a", "e", "i", "o", "u"], vowelsEntered, {
target: inputRef,
});
useKey(["A", "E", "I", "O", "U"], capitalVowelsEntered, {
target: inputRef,
});
return (
<>
Press enter anywhere to trigger a console.log statement
Press a,e,i,o,u in the input to trigger a console.log statement
Press A,E,I,O,U in the input to trigger a different log statement
>
);
}
```
--------------------------------
### Using useDebouncedValue Hook for Input Debouncing in React
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useDebouncedValue.md
This example demonstrates how to integrate the `useDebouncedValue` hook into a React functional component to debounce an input field's value. It illustrates the setup with `useState` for the original value and the hook for the debounced value, along with the optional `immediatelyUpdateDebouncedValue` function. The debounced output is then rendered in the UI.
```JSX
import React, { useState } from "react";
import { useDebouncedValue } from "rooks";
export default function App() {
const [value, setValue] = useState("");
const [debouncedValue, immediatelyUpdateDebouncedValue] = useDebouncedValue(
value,
500
);
// use `immediatelyUpdateDebouncedValue` if you want to update `debouncedValue` immediately
return (
);
}
```
--------------------------------
### Basic Usage of useOnClickRef Hook in React (TypeScript)
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useOnClickRef.md
This example demonstrates the basic import and invocation of the `useOnClickRef` hook within a React functional component. It shows how to include the hook from the 'rooks' library, setting up the foundational structure for its use, though without a specific ref or callback in this minimal illustration.
```TypeScript
import { useOnClickRef } from "rooks";
export default function App() {
useOnClickRef();
return null;
}
```
--------------------------------
### Basic Usage of useOnClickRef Hook in TypeScript
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useOnClickRef.mdx
This example demonstrates the basic integration of the `useOnClickRef` hook from the 'rooks' library into a React functional component. It shows how to import the hook and call it, typically to attach an event listener to a DOM element referenced by a ref.
```TypeScript
import { useOnClickRef } from "rooks";
export default function App() {
useOnClickRef();
return null;
}
```
--------------------------------
### Basic Usage of useSafeSetState in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useSafeSetState.mdx
This example demonstrates the basic integration of the `useSafeSetState` hook within a React functional component. It shows how to import the hook from the 'rooks' library and call it directly within the component's body, ensuring state updates are safely handled even if the component unmounts.
```TypeScript
import {useSafeSetState} from "rooks"
export default function App() {
useSafeSetState();
return null
}
```
--------------------------------
### Basic Usage of useSpeech Hook in React TSX
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useSpeech.md
This example demonstrates the basic usage of the `useSpeech` hook from the 'rooks' library within a React functional component. It imports the hook and calls it, returning `null` as it primarily handles side effects related to speech synthesis.
```TypeScript
import {useSpeech} from "rooks"
export default function App() {
useSpeech();
return null
}
```
--------------------------------
### Using useDeepCompareEffect in React
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useDeepCompareEffect.md
This example demonstrates the basic usage of the `useDeepCompareEffect` hook within a React functional component. It imports the hook from the 'rooks' library and calls it without any arguments, serving as a placeholder for actual dependency usage.
```TypeScript
import {useDeepCompareEffect} from "rooks"
export default function App() {
useDeepCompareEffect();
return null
}
```
--------------------------------
### Listening for Multiple Keyboard Event Types with useKeyRef (JSX)
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useKeyRef.mdx
This example demonstrates how to configure `useKeyRef` to listen for multiple types of keyboard events (e.g., `keypress`, `keydown`, `keyup`) for a single key. By passing an `eventTypes` array in the options, the hook triggers the callback for each specified event type when the 'Enter' key is interacted with.
```jsx
import { useKeyRef } from "rooks";
export default function App() {
function onKeyInteraction(e) {
console.log("[Demo 2]Enter key", e.type);
}
const inputRef = useKeyRef(["Enter"], onKeyInteraction, {
eventTypes: ["keypress", "keydown", "keyup"]
});
return (
<>
Try "Enter" Keypress keydown and keyup
It will log 3 events on this input. Since you can listen to multiple
types of events on a keyboard key.
>
);
}
```
--------------------------------
### Basic Usage of useWhyDidYouUpdate Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useWhyDidYouUpdate.mdx
This example demonstrates the basic integration of the `useWhyDidYouUpdate` hook within a React functional component. It shows how to import the hook from the 'rooks' library and call it inside an `App` component to enable rerender tracking.
```TypeScript
import {useWhyDidYouUpdate} from "rooks"
export default function App() {
useWhyDidYouUpdate();
return null
}
```
--------------------------------
### Basic Usage of useSafeSetState Hook in React
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useSafeSetState.md
This example demonstrates the basic usage of the `useSafeSetState` hook from the 'rooks' library within a React functional component. It ensures that state updates are ignored if the component has unmounted, preventing memory leaks and errors.
```TypeScript
import {useSafeSetState} from "rooks"
export default function App() {
useSafeSetState();
return null
}
```
--------------------------------
### Managing Queue State with useQueueState in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useQueueState.mdx
This example demonstrates the `useQueueState` hook to manage a queue of numbers. It shows how to `enqueue` new items and `dequeue` existing ones, visualizing the queue operations with Framer Motion for animations and styled-components for styling. The `App` component initializes the queue and provides buttons to interact with it.
```jsx
import React, { useRef } from "react";
import "./styles.css";
import { useQueueState } from "rooks";
import { AnimatePresence, motion } from "framer-motion";
import styled from "styled-components";
const variants = {
appear: {
opacity: 0,
y: "-150%",
x: "-15%",
rotate: -15,
transition: {
duration: 0.5,
},
},
disappear: {
opacity: 0,
y: "-200%",
x: "100%",
rotate: 45,
transition: {
duration: 0.5,
},
},
visible: {
opacity: 1,
y: "0%",
x: "0%",
rotate: 0,
transition: {
duration: 0.5,
},
},
};
const StackInner = styled(motion.div)`
border-bottom: 5px solid black;
padding: 0 12px 3px;
width: 300px;
> * {
margin: 0;
padding: 12px 16px;
}
`;
export function StackDiv({ children, ...props }) {
return (
{children}
);
}
export const StackItem = styled(motion.div).attrs(props => ({
variants,
initial: "appear",
animate: "visible",
exit: "disappear",
}))`
width: 100%;
background-color: rgba(254, 243, 199, 1);
margin: 0;
padding: 12px 16px;
font-weight: 500;
font-size: 1rem;
line-height: 1.5rem;
border-color: rgba(0, 0, 0, 1);
border-width: 1px;
border-style: solid;
border-radius: 0.375rem;
place-content: center;
display: flex;
`;
export const ActionButton = styled(motion.button)`
width: 100%;
font-weight: 500;
color: rgba(67,56,202,1);
font-size: 1rem;
line-height: 1.5rem;
padding-top: 0.75rem;
padding-bottom: 0.75rem;
padding-left: 1.5rem;
padding-right: 1.5rem;
border-color: transparent;
align-items: center;
display: inline-flex;
border-radius: 0.375rem;
border-color: transparent;
background-color: rgba(224,231,255,1);
}
`;
export const ActionButton2 = styled(motion.button)`
width: 100%;
font-weight: 500;
font-size: 1rem;
line-height: 1.5rem;
padding-top: 0.75rem;
padding-bottom: 0.75rem;
padding-left: 1.5rem;
padding-right: 1.5rem;
border-color: transparent;
align-items: center;
display: inline-flex;
border-radius: 0.375rem;
border-color: transparent;
background-color: rgba(254, 226, 226, 1);
`;
export const ActionButtons = styled.div`
margin: 12px 0;
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 16px;
`;
export const Root = styled.div`
height: 100vh;
padding-bottom: 100px;
width: 300px;
display: flex;
align-items: flex-end;
margin: auto;
box-sizing: border-box;
`;
export default function App() {
const numberToPushRef = useRef(3);
const [list, { enqueue, dequeue }] = useQueueState([1, 2, 3]);
function addToStack() {
numberToPushRef.current = numberToPushRef.current + 1;
enqueue(numberToPushRef.current);
}
return (
{list.map(item => {
return {item} ;
})}
enqueue {" "}
dequeue
{" "}
);
}
```
--------------------------------
### Basic Counter with useLocalstorageState (JSX)
Source: https://github.com/imbhargav5/rooks/blob/main/data/docs/useLocalstorageState.md
This example demonstrates the fundamental use of `useLocalstorageState` to manage a numerical counter. The counter's value is automatically saved to and retrieved from `localStorage` under the key 'my-app:count', ensuring persistence across page refreshes. It shows how to initialize the state, update it, and clear it using buttons.
```jsx
import "./styles.css";
import React from "react";
import { useLocalstorageState } from "rooks";
export default function App() {
const [count, setCount] = useLocalstorageState("my-app:count", 0);
return (
Rooks : useLocalstorageState
Refresh the page to see the previous value in tact
setCount(0)}>clear
setCount(count + 1)}>Click me {count}
);
}
```
--------------------------------
### Importing Dependencies and Defining Constants in React
Source: https://github.com/imbhargav5/rooks/blob/main/apps/website/content/docs/hooks/useKey.mdx
This snippet imports all necessary React hooks, utility hooks from the 'rooks' library, 'random' for number generation, 'styled-components' for CSS-in-JS, and 'framer-motion' for animations. It also defines a 'colors' array for styling and an 'Alphabets' array used for key press detection.
```jsx
import React, { useRef, useState } from "react";
import "./styles.css";
import { useDebounce, useKey, useThrottle, useTimeoutWhen } from "rooks";
import random from "random";
import styled from "styled-components";
import { AnimatePresence, motion } from "framer-motion";
const colors = [
"#1D4ED8",
"#6D28D9",
"#92400E",
"#047857",
"#DC2626",
"#374151",
"##BE185D"
];
const Alphabets = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z"
];
```