Hello everyone, today we are introducing react-use. Between you and me, the first time I saw this, I thought I found Beau. React hooks this library implements basically all of the custom hooks we see all the time, which need to be copied to your project directly from the source code

  • Github is a huge repository of great projects. In fact, it is not necessarily the projects with many stars that deserve attention. There are many small and beautiful projects that we can pay attention to and timely fork. Standing on the shoulders of predecessors to build wheels or directly applied to the project, so as not to be afraid of 🙅🏻♀️ roll. We strive to use the shortest article every day, the shortest time, to bring you the greatest benefits.

ℹ️ is the essential set of React Hooks.


The react – use for details

1 The sensor

  • useBattery– Trace the battery status of the device.

  • useGeolocation– Track the location status of user devices.

  • useHover and useHoverDirty– Tracks the state of an element when the mouse hovers over it.

  • useHash– Trace user hash changes.

  • UseIdle – Tracks whether the user is inactive.

  • useIntersection— Trace element’s window change area (for lazy loading IntersectionObserver)

  • useKey.useKeyPress.useKeyboardJs, and useKeyPressEvent— Tracking buttons.

  • UseLocation and useSearchParam – Tracks the location status of the navigation bar on a page.

  • UseLongPress — Long press gestures that track certain elements.

  • useMedia– Trace the CSS media query status.

  • UseMediaDevices – Tracks the status of connected hardware devices.

  • UseMotion – Tracks the status of the device’s motion sensors.

  • useMouse and useMouseHovered– Track the mouse position.

  • useMouseWheel— Track deltaY for scrolling mouse wheel.

  • useNetworkState– Trace the network connection status of the browser.

  • UseOrientation – Tracks the device screen orientation.

  • UsePageLeave – Triggered when the mouse leaves the page boundary.

  • UseScratch – Tracks mouse click and slide states.

  • useScroll– Tracks the scrolling position of HTML elements.

  • UseScrolling – Tracks whether HTML elements are scrolling.

  • UseStartTyping – Detects when a user starts typing.

  • useWindowScroll– Trace the scroll position of the window.

  • useWindowSize– Trace window size.

  • useMeasure and useSize– Tracks the size of HTML elements.

  • CreateBreakpoint – Trace innerWidth

  • useScrollbarWidth– Checks the browser’s native scroll bar width.

2 UI

  • useAudio– Plays the audio and displays its controls.

  • UseClickAway – Triggers a callback when the user clicks outside the target area.

  • UseCss – Dynamically adjust CSS.

  • UseDrop and useDropArea – Track files, links, and copy-paste placement.

  • useFullscreen– Displays elements or videos in full screen.

  • useSlider– Provides sliding behavior on any HTML element.

  • useSpeech– Synthesizes speech from text strings.

  • useVibrate— Provide physical feedback using vibration API.Vibration API.

  • useVideo– Plays a video, traces its status, and displays the playback control.

3 Animations

  • UseRaf – Rerenders the component on each requestAnimationFrame.

  • UseInterval and useHarmonicIntervalFn – use setInterval to re-render components at a setInterval.

  • UseSpring — Insert numbers over time based on spring dynamics.

  • UseTimeout – Re-render components after a timeout.

  • useTimeoutFn– Invoke the specified function after timeout.

  • useTween– Re-render components while tween numbers from 0 to 1.

  • UseUpdate – Returns a callback that rerenders the component when called.

4 Side-effects

  • UseAsync, useAsyncFn, and useAsyncRetry – Resolves asynchronous functions.

  • UseBeforeUnload – Displays browser alerts when a user tries to reload or close a page.

  • useCookie– Provides methods to read, update, and delete cookies.

  • UseCopyToClipboard – Copies text to the clipboard.

  • useDebounce— function to shake]

  • useError– Incorrect scheduler.

  • UseFavicon – Sets the favicon of the page.

  • UseLocalStorage – Manages values in localStorage.

  • UseLockBodyScroll – Locks the scroll of the body element.

  • UseRafLoop – Calls the given function within the RAF loop.

  • UseSessionStorage – Manages the values in sessionStorage.

  • useThrottle and useThrottleFn– throttles a function.

  • UseTitle – The title of the page.

  • UsePermission – Queries the permission status of the browser API.

5 Lifecycles

  • UseEffectOnce – Modified useEffect hook that runs only once.

  • UseEvent – Subscribe events.

  • UseLifecycles — Calls mount and unmount callbacks.

  • UseMountedState and useUnmountPromise – Whether the tracer component is installed.

  • UsePromise — High similarity promise only while component is mounted

  • UseLogger – Console prints as the component goes through its life cycle.

  • UseMount – Invoke the mount callback.

  • UseUnmount – Invoke the unmount callback.

  • UseUpdateEffect – Runs effects only for updates.

  • UseIsomorphicLayoutEffect – the server does not display a warning useLayoutEffect when rendering.

  • UseDeepCompareEffect, useShallowCompareEffect, and useCustomCompareEffect – Compare runtime effects based on the depth of their dependencies

6 State

  • CreateMemo — Memory hook Factory.

  • CreateReducer – A Reducer hook factory with custom middleware.

  • CreateReducerContext and createStateContext – Hook factories that share state between components.

  • UseDefault – Returns the default value when state is null or undefined.

  • UseGetSet – Returns the getter get() for the state instead of the original state.

  • UseGetSetState — as if useGetSet and useSetState had a baby.

  • UseLatest – Returns the latest state or props

  • usePrevious– Returns the latest state or props.

  • UsePreviousDistinct – Similar to usePrevious, but using predicates to determine whether previous content should be updated.

  • UseObservable – Tracks the latest value of an Observable.

  • useRafStateCreate a setState method that updates only after requestAnimationFrame.

  • useSetState– Create a setState method similar to this.setState.

  • useStateList– Loop through an array.

  • useToggle and useBoolean– Tracks the status of booleans.

  • useCounter and useNumber– Trace the status of digits.

  • useList and useUpsert– Tracks the status of arrays.

  • useMap– Trace object status.

  • useSet– Trace the status of Set.

  • UseQueue – Implements a simple queue.

  • useStateValidator– Trace object status.

  • useStateWithHistory– Stores previous state values and provides a handle to traverse them.

  • useMultiStateValidator– Similar to useStateValidator, but tracks multiple states at a time.

  • useMediatedState– Similar to regular useState, but mediated by custom functions.

  • useFirstMountStateCheck if the current render is the first.

  • useRendersCount– Compute component rendering.

  • createGlobalState– Shared status across components.

  • useMethods— A concise alternative to useReducer.

7 All kinds of other things

  • UseEnsuredForwardedRef and ensuredForwardRef — Use react. forwardedRef safely.

8. Go straight to the code demo

import {useBattery} from 'react-use';

const Demo = () = > {
  const batteryState = useBattery();

  if(! batteryState.isSupported) {return (
      <div>
        <strong>Battery sensor</strong>: <span>not supported</span>
      </div>
    );
  }

  if(! batteryState.fetched) {return (
      <div>
        <strong>Battery sensor</strong>: <span>supported</span> <br />
        <strong>Battery state</strong>: <span>fetching</span>
      </div>
    );
  }

  return (
    <div>
      <strong>Battery sensor</strong>:&nbsp;&nbsp; <span>supported</span> <br />
      <strong>Battery state</strong>: <span>fetched</span> <br />
      <strong>Charge level</strong>:&nbsp;&nbsp; <span>{ (batteryState.level * 100).toFixed(0) }%</span> <br />
      <strong>Charging</strong>:&nbsp;&nbsp; <span>{ batteryState.charging ? 'yes' : 'no' }</span> <br />
      <strong>Charging time</strong>:&nbsp;&nbsp;
      <span>{ batteryState.chargingTime ? batteryState.chargingTime : 'finished' }</span> <br />
      <strong>Discharging time</strong>:&nbsp;&nbsp; <span>{ batteryState.dischargingTime }</span>
    </div>
  );
};
Copy the code

9. Front-end technical AC group of grounding gas

  • There are more than 10,000 front end students gathered here, irregular open classes, special classes. Daily morning front morning reading class, afternoon workplace topic links

Thank you again for taking the time to read this little article, if you have anything to say please leave it in the comments below ~

By Lao Yuan September 08, 2021