Created
December 9, 2024 21:26
-
-
Save carloitaben/996a6014cf978a7271532fce249ffc30 to your computer and use it in GitHub Desktop.
React 19 merge refs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import type { Ref } from "react" | |
| function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): Ref<T> { | |
| return (value) => { | |
| const cleanups = refs.reduce<VoidFunction[]>((accumulator, ref) => { | |
| if (typeof ref === "function") { | |
| const cleanup = ref(value) | |
| if (typeof cleanup === "function") { | |
| accumulator.push(cleanup) | |
| } | |
| } else if (ref) { | |
| ref.current = value | |
| } | |
| return accumulator | |
| }, []) | |
| return () => { | |
| cleanups.forEach((cleanup) => cleanup()) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment