@restart/hooks

  • Version 0.4.0
  • Published
  • 180 kB
  • 1 dependency
  • MIT license

Install

npm i @restart/hooks
yarn add @restart/hooks
pnpm add @restart/hooks

Overview

A set of utility and general-purpose React hooks.

Index

Functions

function useCallbackRef

useCallbackRef: <TValue = unknown>() => [TValue, (ref: TValue | null) => void];
  • A convenience hook around useState designed to be paired with the component [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs) api. Callback refs are useful over useRef() when you need to respond to the ref being set instead of lazily accessing it in an effect.

    const [element, attachRef] = useCallbackRef<HTMLDivElement>()
    useEffect(() => {
    if (!element) return
    const calendar = new FullCalendar.Calendar(element)
    return () => {
    calendar.destroy()
    }
    }, [element])
    return <div ref={attachRef} />

    refs

function useCommittedRef

useCommittedRef: <TValue>(value: TValue) => any;
  • Creates a Ref whose value is updated in an effect, ensuring the most recent value is the one rendered with. Generally only required for Concurrent mode usage where previous work in render() may be discarded befor being used.

    This is safe to access in an event handler.

    Parameter value

    The Ref value

function useEventCallback

useEventCallback: <TCallback extends (...args: any[]) => any>(
fn?: TCallback | null
) => TCallback;

    function useEventListener

    useEventListener: <
    T extends Element | Document | Window,
    K extends keyof DocumentEventMap
    >(
    eventTarget: T | (() => T),
    event: K,
    listener: EventHandler<T, K>,
    capture?: boolean | AddEventListenerOptions
    ) => void;
    • Attaches an event handler outside directly to specified DOM element bypassing the react synthetic event system.

      Parameter element

      The target to listen for events on

      Parameter event

      The DOM event name

      Parameter handler

      An event handler

      Parameter capture

      Whether or not to listen during the capture event phase

    function useGlobalListener

    useGlobalListener: <K extends keyof DocumentEventMap>(
    event: K,
    handler: DocumentEventHandler<K>,
    capture?: boolean | AddEventListenerOptions
    ) => void;
    • Attaches an event handler outside directly to the document, bypassing the react synthetic event system.

      useGlobalListener('keydown', (event) => {
      console.log(event.key)
      })

      Parameter event

      The DOM event name

      Parameter handler

      An event handler

      Parameter capture

      Whether or not to listen during the capture event phase

    function useImage

    useImage: (
    imageOrUrl?: string | HTMLImageElement | null | undefined,
    crossOrigin?: 'anonymous' | 'use-credentials' | string
    ) => State;
    • Fetch and load an image for programatic use such as in a <canvas> element.

      Parameter imageOrUrl

      The HtmlImageElement or image url to load

      Parameter crossOrigin

      The crossorigin attribute to set

      const { image, error } = useImage('/static/kittens.png')
      const ref = useRef<HTMLCanvasElement>()
      useEffect(() => {
      const ctx = ref.current.getContext('2d')
      if (image) {
      ctx.drawImage(image, 0, 0)
      }
      }, [ref, image])
      return (
      <>
      {error && "there was a problem loading the image"}
      <canvas ref={ref} />
      </>

    function useInterval

    useInterval: {
    (fn: () => void, ms: number): void;
    (fn: () => void, ms: number, paused: boolean): void;
    (fn: () => void, ms: number, paused: boolean, runImmediately: boolean): void;
    };
    • Creates a setInterval that is properly cleaned up when a component unmounted

      function Timer() {
      const [timer, setTimer] = useState(0)
      useInterval(() => setTimer(i => i + 1), 1000)
      return <span>{timer} seconds past</span>
      }

      Parameter fn

      an function run on each interval

      Parameter ms

      The milliseconds duration of the interval

    • Creates a pausable setInterval that is properly cleaned up when a component unmounted

      const [paused, setPaused] = useState(false)
      const [timer, setTimer] = useState(0)
      useInterval(() => setTimer(i => i + 1), 1000, paused)
      return (
      <span>
      {timer} seconds past
      <button onClick={() => setPaused(p => !p)}>{paused ? 'Play' : 'Pause' }</button>
      </span>
      )

      Parameter fn

      an function run on each interval

      Parameter ms

      The milliseconds duration of the interval

      Parameter paused

      Whether or not the interval is currently running

    • Creates a pausable setInterval that _fires_ immediately and is properly cleaned up when a component unmounted

      const [timer, setTimer] = useState(-1)
      useInterval(() => setTimer(i => i + 1), 1000, false, true)
      // will update to 0 on the first effect
      return <span>{timer} seconds past</span>

      Parameter fn

      an function run on each interval

      Parameter ms

      The milliseconds duration of the interval

      Parameter paused

      Whether or not the interval is currently running

      Parameter runImmediately

      Whether to run the function immediately on mount or unpause rather than waiting for the first interval to elapse

    function useMergeState

    useMergeState: <TState extends {}>(
    initialState: TState | (() => TState)
    ) => [TState, MergeStateSetter<TState>];
    • Mimics a React class component's state model, of having a single unified state object and an updater that merges updates into the existing state, as opposed to replacing it.

      const [state, setState] = useMergeState({ name: 'Betsy', age: 24 })
      setState({ name: 'Johan' }) // { name: 'Johan', age: 24 }
      setState(state => ({ age: state.age + 10 })) // { name: 'Johan', age: 34 }

      Parameter initialState

      The initial state object

    function useMergeStateFromProps

    useMergeStateFromProps: <TProps, TState>(
    props: TProps,
    gDSFP: Mapper<TProps, TState>,
    initialState: TState
    ) => [TState, MergeStateSetter<TState>];

      function useMounted

      useMounted: () => () => boolean;
      • Track whether a component is current mounted. Generally less preferable than properlly canceling effects so they don't run after a component is unmounted, but helpful in cases where that isn't feasible, such as a Promise resolution.

        Returns

        a function that returns the current isMounted state of the component

        const [data, setData] = useState(null)
        const isMounted = useMounted()
        useEffect(() => {
        fetchdata().then((newData) => {
        if (isMounted()) {
        setData(newData);
        }
        })
        })

      function usePrevious

      usePrevious: <T>(value: T) => T | null;
      • Store the last of some value. Tracked via a Ref only updating it after the component renders.

        Helpful if you need to compare a prop value to it's previous value during render.

        function Component(props) {
        const lastProps = usePrevious(props)
        if (lastProps.foo !== props.foo)
        resetValueFromProps(props.foo)
        }

        Parameter value

        the value to track

      function useRafInterval

      useRafInterval: (fn: () => void, ms: number) => void;

        function useResizeObserver

        useResizeObserver: <TElement extends Element>(
        element: TElement | null | undefined
        ) => Rect | null;
        • Efficiently observe size changes on an element. Depends on the ResizeObserver api, and polyfills are needed in older browsers.

          const [ref, attachRef] = useCallbackRef(null);
          const rect = useResizeObserver(ref);
          return (
          <div ref={attachRef}>
          {JSON.stringify(rect)}
          </div>
          )

          Parameter element

          The DOM element to observe

        Package Files (14)

        Dependencies (1)

        Dev Dependencies (0)

        No dev dependencies.

        Peer Dependencies (1)

        Badge

        To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

        You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@restart/hooks.

        • Markdown
          [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@restart/hooks)
        • HTML
          <a href="https://www.jsdocs.io/package/@restart/hooks"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>