Top Related Projects
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
🐻 Bear necessities for state management in React
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
React Hooks for Data Fetching
RFCs for changes to React
Quick Overview
react-use is a comprehensive collection of essential React hooks that aims to enhance the development experience and reduce boilerplate code. It provides a wide range of hooks for various purposes, including state management, side effects, animations, and more, allowing developers to build robust React applications with ease.
Pros
- Extensive collection of hooks covering many common use cases
- Well-documented with examples and TypeScript support
- Actively maintained with frequent updates and contributions
- Modular design allows for easy cherry-picking of specific hooks
Cons
- Large number of hooks may be overwhelming for beginners
- Some hooks might have performance implications if not used carefully
- Potential dependency on external libraries for certain hooks
- May increase bundle size if not properly tree-shaken
Code Examples
- Using the
useToggle
hook for a simple toggle state:
import { useToggle } from 'react-use';
const ToggleComponent = () => {
const [isOn, toggle] = useToggle(false);
return (
<button onClick={toggle}>
{isOn ? 'ON' : 'OFF'}
</button>
);
};
- Implementing a debounced input with
useDebounce
:
import { useDebounce } from 'react-use';
const DebouncedInput = () => {
const [value, setValue] = useState('');
const debouncedValue = useDebounce(value, 500);
return (
<input
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Type to search..."
/>
);
};
- Using
useLocalStorage
for persistent state:
import { useLocalStorage } from 'react-use';
const PersistentCounter = () => {
const [count, setCount] = useLocalStorage('counter', 0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
Getting Started
To start using react-use in your project:
-
Install the package:
npm install react-use
-
Import and use hooks in your components:
import { useToggle, useDebounce } from 'react-use'; const MyComponent = () => { const [isVisible, toggle] = useToggle(false); const debouncedValue = useDebounce(someValue, 300); // Use the hooks in your component logic };
-
Refer to the official documentation for detailed usage instructions and available hooks.
Competitor Comparisons
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
Pros of TanStack Query
- Specialized for data fetching and state management
- Built-in caching and automatic background updates
- Extensive documentation and strong community support
Cons of TanStack Query
- Steeper learning curve for beginners
- More opinionated approach to data management
- Limited to data fetching and caching use cases
Code Comparison
react-use:
import { useAsync } from 'react-use';
const MyComponent = () => {
const state = useAsync(async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
}, []);
if (state.loading) return 'Loading...';
if (state.error) return 'Error!';
return <div>{JSON.stringify(state.value)}</div>;
};
TanStack Query:
import { useQuery } from '@tanstack/react-query';
const MyComponent = () => {
const { isLoading, error, data } = useQuery('myData', async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
});
if (isLoading) return 'Loading...';
if (error) return 'Error!';
return <div>{JSON.stringify(data)}</div>;
};
Summary
TanStack Query excels in data fetching and state management with built-in caching, while react-use offers a broader set of utility hooks for various React use cases. TanStack Query provides a more specialized solution for data-heavy applications, whereas react-use is more versatile for general React development needs.
🐻 Bear necessities for state management in React
Pros of zustand
- Simpler API with less boilerplate compared to react-use
- Built-in support for middleware and devtools
- Better performance for large state updates
Cons of zustand
- Less comprehensive collection of hooks and utilities
- Steeper learning curve for developers new to state management
- Limited built-in TypeScript support compared to react-use
Code Comparison
zustand:
import create from 'zustand'
const useStore = create(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
}))
react-use:
import { useCounter } from 'react-use'
const [count, { inc }] = useCounter(0)
Summary
zustand offers a more streamlined approach to state management with better performance for complex state updates. It provides built-in middleware support and devtools integration. However, it has a steeper learning curve and fewer utility hooks compared to react-use.
react-use, on the other hand, provides a comprehensive collection of hooks and utilities, making it easier for developers to adopt and use in various scenarios. It has better TypeScript support out of the box but may not perform as well for large state updates.
The choice between the two depends on the specific needs of your project, such as the complexity of state management required and the preference for a more opinionated (zustand) or flexible (react-use) approach.
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
Pros of TanStack Query
- Specialized for data fetching and state management
- Built-in caching and automatic background updates
- Extensive documentation and strong community support
Cons of TanStack Query
- Steeper learning curve for beginners
- More opinionated approach to data management
- Limited to data fetching and caching use cases
Code Comparison
react-use:
import { useAsync } from 'react-use';
const MyComponent = () => {
const state = useAsync(async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
}, []);
if (state.loading) return 'Loading...';
if (state.error) return 'Error!';
return <div>{JSON.stringify(state.value)}</div>;
};
TanStack Query:
import { useQuery } from '@tanstack/react-query';
const MyComponent = () => {
const { isLoading, error, data } = useQuery('myData', async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
});
if (isLoading) return 'Loading...';
if (error) return 'Error!';
return <div>{JSON.stringify(data)}</div>;
};
Summary
TanStack Query excels in data fetching and state management with built-in caching, while react-use offers a broader set of utility hooks for various React use cases. TanStack Query provides a more specialized solution for data-heavy applications, whereas react-use is more versatile for general React development needs.
React Hooks for Data Fetching
Pros of SWR
- Focused specifically on data fetching and caching
- Built-in support for real-time and optimistic updates
- Lightweight and easy to integrate with existing projects
Cons of SWR
- Limited to data fetching use cases
- Requires more setup for complex scenarios
- Less flexibility compared to react-use's diverse hook collection
Code Comparison
SWR:
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
return <div>Hello {data.name}!</div>
}
react-use:
import { useAsync } from 'react-use'
function Profile() {
const state = useAsync(async () => {
const response = await fetch('/api/user')
return response.json()
})
if (state.loading) return <div>Loading...</div>
if (state.error) return <div>Failed to load</div>
return <div>Hello {state.value.name}!</div>
}
SWR is more specialized for data fetching, offering built-in caching and real-time updates. react-use provides a wider range of hooks for various use cases, including data fetching. SWR's API is simpler for basic data fetching scenarios, while react-use offers more flexibility and control over the fetching process.
RFCs for changes to React
Pros of rfcs
- Official React repository for discussing and proposing changes
- Provides a structured process for community input on React's future
- Offers in-depth technical discussions and rationales for proposed features
Cons of rfcs
- Focused on proposals rather than ready-to-use code
- May not provide immediate solutions for developers' current needs
- Can be more theoretical and less practical for day-to-day development
Code comparison
rfcs typically doesn't contain implementation code, but rather proposal descriptions. react-use, on the other hand, provides ready-to-use custom hooks:
react-use:
import { useToggle } from 'react-use';
const [isOn, toggleIsOn] = useToggle(false);
rfcs:
# RFC: New Hook Proposal
## Summary
This RFC proposes a new React hook called `useToggle`...
Summary
rfcs is an official React repository for discussing and proposing changes to the React library. It offers a structured process for community input and in-depth technical discussions. However, it focuses on proposals rather than ready-to-use code and may not provide immediate solutions for developers.
react-use, in contrast, is a collection of ready-to-use custom React hooks that developers can immediately implement in their projects. It offers practical solutions for common use cases but may not provide the same level of in-depth discussion or official backing as rfcs.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ð
react-use
Collection of essential React Hooks. Port of
libreact
.
Translations: ð¨ð³ æ±è¯
npm i react-use
- Sensors
useBattery
— tracks device battery state.useGeolocation
— tracks geo location state of user's device.useHover
anduseHoverDirty
— tracks mouse hover state of some element.useHash
— tracks location hash value.useIdle
— tracks whether user is being inactive.useIntersection
— tracks an HTML element's intersection.useKey
,useKeyPress
,useKeyboardJs
, anduseKeyPressEvent
— track keys.useLocation
anduseSearchParam
— tracks page navigation bar location state.useLongPress
— tracks long press gesture of some element.useMedia
— tracks state of a CSS media query.useMediaDevices
— tracks state of connected hardware devices.useMotion
— tracks state of device's motion sensor.useMouse
anduseMouseHovered
— tracks state of mouse position.useMouseWheel
— tracks deltaY of scrolled mouse wheel.useNetworkState
— tracks the state of browser's network connection.useOrientation
— tracks state of device's screen orientation.usePageLeave
— triggers when mouse leaves page boundaries.useScratch
— tracks mouse click-and-scrub state.useScroll
— tracks an HTML element's scroll position.useScrolling
— tracks whether HTML element is scrolling.useStartTyping
— detects when user starts typing.useWindowScroll
— tracksWindow
scroll position.useWindowSize
— tracksWindow
dimensions.useMeasure
anduseSize
— tracks an HTML element's dimensions.createBreakpoint
— tracksinnerWidth
useScrollbarWidth
— detects browser's native scrollbars width.usePinchZoom
— tracks pointer events to detect pinch zoom in and out status.
- UI
useAudio
— plays audio and exposes its controls.useClickAway
— triggers callback when user clicks outside target area.useCss
— dynamically adjusts CSS.useDrop
anduseDropArea
— tracks file, link and copy-paste drops.useFullscreen
— display an element or video full-screen.useSlider
— provides slide behavior over any HTML element.useSpeech
— synthesizes speech from a text string.useVibrate
— provide physical feedback using the Vibration API.useVideo
— plays video, tracks its state, and exposes playback controls.
- Animations
useRaf
— re-renders component on eachrequestAnimationFrame
.useInterval
anduseHarmonicIntervalFn
— re-renders component on a set interval usingsetInterval
.useSpring
— interpolates number over time according to spring dynamics.useTimeout
— re-renders component after a timeout.useTimeoutFn
— calls given function after a timeout.useTween
— re-renders component, while tweening a number from 0 to 1.useUpdate
— returns a callback, which re-renders component when called.
- Side-effects
useAsync
,useAsyncFn
, anduseAsyncRetry
— resolves anasync
function.useBeforeUnload
— shows browser alert when user try to reload or close the page.useCookie
— provides way to read, update and delete a cookie.useCopyToClipboard
— copies text to clipboard.useDebounce
— debounces a function.useError
— error dispatcher.useFavicon
— sets favicon of the page.useLocalStorage
— manages a value inlocalStorage
.useLockBodyScroll
— lock scrolling of the body element.useRafLoop
— calls given function inside the RAF loop.useSessionStorage
— manages a value insessionStorage
.useThrottle
anduseThrottleFn
— throttles a function.useTitle
— sets title of the page.usePermission
— query permission status for browser APIs.
- Lifecycles
useEffectOnce
— a modifieduseEffect
hook that only runs once.useEvent
— subscribe to events.useLifecycles
— callsmount
andunmount
callbacks.useMountedState
anduseUnmountPromise
— track if component is mounted.usePromise
— resolves promise only while component is mounted.useLogger
— logs in console as component goes through life-cycles.useMount
— callsmount
callbacks.useUnmount
— callsunmount
callbacks.useUpdateEffect
— run aneffect
only on updates.useIsomorphicLayoutEffect
—useLayoutEffect
that that works on server.useDeepCompareEffect
,useShallowCompareEffect
, anduseCustomCompareEffect
- State
createMemo
— factory of memoized hooks.createReducer
— factory of reducer hooks with custom middleware.createReducerContext
andcreateStateContext
— factory of hooks for a sharing state between components.useDefault
— returns the default value when state isnull
orundefined
.useGetSet
— returns state getterget()
instead of raw state.useGetSetState
— as ifuseGetSet
anduseSetState
had a baby.useLatest
— returns the latest state or propsusePrevious
— returns the previous state or props.usePreviousDistinct
— likeusePrevious
but with a predicate to determine ifprevious
should update.useObservable
— tracks latest value of anObservable
.useRafState
— createssetState
method which only updates afterrequestAnimationFrame
.useSetState
— createssetState
method which works likethis.setState
.useStateList
— circularly iterates over an array.useToggle
anduseBoolean
— tracks state of a boolean.useCounter
anduseNumber
— tracks state of a number.useList
and— tracks state of an array.useUpsert
useMap
— tracks state of an object.useSet
— tracks state of a Set.useQueue
— implements simple queue.useStateValidator
— tracks state of an object.useStateWithHistory
— stores previous state values and provides handles to travel through them.useMultiStateValidator
— alike theuseStateValidator
, but tracks multiple states at a time.useMediatedState
— like the regularuseState
but with mediation by custom function.useFirstMountState
— check if current render is first.useRendersCount
— count component renders.createGlobalState
— cross component shared state.useMethods
— neat alternative touseReducer
.
- Miscellaneous
useEnsuredForwardedRef
andensuredForwardRef
— use a React.forwardedRef safely.
Usage — how to import.
Unlicense — public domain.
Support — add yourself to backer list below.
Contributors
Top Related Projects
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
🐻 Bear necessities for state management in React
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
React Hooks for Data Fetching
RFCs for changes to React
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot