Skip to content

Commit

Permalink
Switch: useMergeRef for forwarding ref
Browse files Browse the repository at this point in the history
Summary:
Changelog:
[Internal] - Replace `useImperativeHandle` usage with new `useMergeRef` which will keep both the forwarded and internal ref handle up to date (in case the instance ever changes). That being said, this change was not motivated in fear of a stale ref but more an intention to show that `useImperativeHandle`'s use case is more about creating a selective API and `useMergeRef` is better suited for publishing ref updates.

Reviewed By: yungsters

Differential Revision: D28950632

fbshipit-source-id: 594afda02693545aab77f24566180c338b58bb8b
  • Loading branch information
Luna Wei authored and facebook-github-bot committed Jun 9, 2021
1 parent 9a43eac commit 0aa8e25
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions Libraries/Components/Switch/Switch.js
Expand Up @@ -12,6 +12,7 @@
import Platform from '../../Utilities/Platform';
import * as React from 'react';
import StyleSheet from '../../StyleSheet/StyleSheet';
import useMergeRefs from '../../Utilities/useMergeRefs';

import AndroidSwitchNativeComponent, {
Commands as AndroidSwitchCommands,
Expand Down Expand Up @@ -153,7 +154,8 @@ const SwitchWithForwardedRef: React.AbstractComponent<
const nativeSwitchRef = React.useRef<React.ElementRef<
typeof SwitchNativeComponent | typeof AndroidSwitchNativeComponent,
> | null>(null);
React.useImperativeHandle(forwardedRef, () => nativeSwitchRef.current);

const ref = useMergeRefs(nativeSwitchRef, forwardedRef);

const [native, setNative] = React.useState({value: null});

Expand Down Expand Up @@ -200,7 +202,7 @@ const SwitchWithForwardedRef: React.AbstractComponent<
onChange={handleChange}
onResponderTerminationRequest={returnsFalse}
onStartShouldSetResponder={returnsTrue}
ref={nativeSwitchRef}
ref={ref}
/>
);
} else {
Expand Down Expand Up @@ -232,7 +234,7 @@ const SwitchWithForwardedRef: React.AbstractComponent<
onChange={handleChange}
onResponderTerminationRequest={returnsFalse}
onStartShouldSetResponder={returnsTrue}
ref={nativeSwitchRef}
ref={ref}
/>
);
}
Expand Down

0 comments on commit 0aa8e25

Please sign in to comment.