UNPKG

1.87 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, useRef} from 'react';
14import {useLayoutEffect} from './';
15
16/**
17 * Offers an object ref for a given callback ref or an object ref. Especially
18 * helfpul when passing forwarded refs (created using `React.forwardRef`) to
19 * React Aria Hooks.
20 *
21 * @param forwardedRef The original ref intended to be used.
22 * @returns An object ref that updates the given ref.
23 * @see https://reactjs.org/docs/forwarding-refs.html
24 */
25export function useObjectRef<T>(forwardedRef?: ((instance: T | null) => void) | MutableRefObject<T | null> | null): MutableRefObject<T> {
26 const objRef = useRef<T>();
27
28 /**
29 * We're using `useLayoutEffect` here instead of `useEffect` because we want
30 * to make sure that the `ref` value is up to date before other places in the
31 * the execution cycle try to read it.
32 */
33 useLayoutEffect(() => {
34 if (!forwardedRef) {
35 return;
36 }
37
38 if (typeof forwardedRef === 'function') {
39 forwardedRef(objRef.current);
40 } else {
41 forwardedRef.current = objRef.current;
42 }
43
44 return () => {
45 if (typeof forwardedRef === 'function') {
46 forwardedRef(null);
47 } else {
48 forwardedRef.current = null;
49 }
50 };
51 }, [forwardedRef]);
52
53 return objRef;
54}