UNPKG

1.53 kBPlain TextView Raw
1/*
2 * Copyright 2021 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13import {MutableRefObject, useMemo, useRef} from 'react';
14
15/**
16 * Offers an object ref for a given callback ref or an object ref. Especially
17 * helfpul when passing forwarded refs (created using `React.forwardRef`) to
18 * React Aria Hooks.
19 *
20 * @param forwardedRef The original ref intended to be used.
21 * @returns An object ref that updates the given ref.
22 * @see https://reactjs.org/docs/forwarding-refs.html
23 */
24export function useObjectRef<T>(forwardedRef?: ((instance: T | null) => void) | MutableRefObject<T | null> | null): MutableRefObject<T> {
25 const objRef = useRef<T>();
26 return useMemo(() => ({
27 get current() {
28 return objRef.current;
29 },
30 set current(value) {
31 objRef.current = value;
32 if (typeof forwardedRef === 'function') {
33 forwardedRef(value);
34 } else if (forwardedRef) {
35 forwardedRef.current = value;
36 }
37 }
38 }), [forwardedRef]);
39}