1.0.4 • Published 1 year ago

reactive-ref v1.0.4

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
1 year ago

React hooks for reactive work with refs.

Why?

:question: Are you working with legacy code? This piece of the good old times sets a ref when it wants to?

:question: Does setTimeout brazenly live in your useEffect to check when the ref will finally not be null?

:question: Is a beautiful third party lib creating a new div right now, giving it the ref, and not notifying you?

Use reactive-ref! This hell is over!

Usage

There are two hooks for you: useReactiveRef and useRefCallback.

useReactiveRef

Rendering starts when .current changes with a new value (checked via Object.is).

import { useReactiveRef } from 'reactive-ref'

const IHandleThirdPartyLibSadly = () => {
  // Types and usage are completely identical to useRef.
  // You can literally just add "Reactive" after "use" in your current code!
  const ref = useReactiveRef<HTMLDivElement>(null)

  useEffect(() => {
    if (ref.current) {
      // 😎 Now you have ref with div, no matter when it gets set
    }
    // We are adding ref.current here because it's now reactive
  }, [ref.current])

  return <HaHaIWillSetRefInASecond ref={ref}></HaHaIWillSetRefInASecond>
}

useRefCallback

Callback is fired when .current changes with a new value (checked via Object.is).

import { useRefCallback } from 'reactive-ref'

const IHandleThirdPartyLibSadlyAgain = () => {
  // The first argument is a callback.
  // The second argument is a initial value.
  const ref = useRefCallback<HTMLDivElement>((theSameRef) => {
    // 😎 I have access to the updated ref immediately without extra renders
  }, null)

  return <HaHaIWillChangeElementEverySecond ref={ref}></HaHaIWillChangeElementEverySecond>
}

When not to use

  • Don't use useReactiveRef to store state. You can, but this goes against React's immutability philosophy.

My Links

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago