useSharedRef
Introduction
With this hook you can use refs
across components without prop drilling. They're stored in a React context instance.
Installation
npm install --save react-use-shared-ref
or yarn add react-use-shared-ref
.
Usage
First wrap your <App />
inside the RefContextProvider
:
import RefContextProvider from 'react-use-shared-ref'; ReactDOM;
To create a (named) ref, you can use the createRef
function that is exposed from the hook. You can then pass this function as a ref to any component.
import useSharedRef from 'react-use-shared-ref'; const Component = const createRef = ; const ref = ; return <ChildComponent = />;
To use the ref in another component, you can use the refs
list.
import useSharedRef from 'react-use-shared-ref'; const SomeOtherComponent = const refs = ; const myRef = refs; // Ref to `ChildComponent`
The ref does not have a current
key as opposed to regular refs
, it is either the current value of the ref
or it is undefined
(not set in the refs
object in the context).