Skip to content

Commit

Permalink
Avoid redundant state updates in Pressable if children and style are …
Browse files Browse the repository at this point in the history
…not functions (#44615)

Summary:
Goal of this PR is to optimise `Pressable` component, similarly to react-native-tvos/react-native-tvos#724 . `Pressable` `style` and `children` properties can, but doesn't have to be functions. Usually we passing objects or arrays. `pressed` state is used only when `style` or `children` are `functions`, so let's update that state only in such case, otherwise let's skip state updates to improve the performance.

 That way we won't have to rerender the component when it is being pressed (assuming that `style` and `children` are not going to be functions)

## Changelog:

[GENERAL] [CHANGED] - Improve performance of `Pressable` component.

Pull Request resolved: #44615

Test Plan: Verify that `Pressable` updates its `pressed` state when `style` or `children` are functions.

Reviewed By: javache

Differential Revision: D57614309

Pulled By: fabriziocucci

fbshipit-source-id: 473e0ab3c4bf7b3ef04ba19f76105ac65371a3fb
  • Loading branch information
Zahoq authored and facebook-github-bot committed May 21, 2024
1 parent cd1ddbb commit cfa784c
Showing 1 changed file with 6 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,9 @@ function Pressable(

const [pressed, setPressed] = usePressState(testOnly_pressed === true);

const shouldUpdatePressed =
typeof children === 'function' || typeof style === 'function';

let _accessibilityState = {
busy: ariaBusy ?? accessibilityState?.busy,
checked: ariaChecked ?? accessibilityState?.checked,
Expand Down Expand Up @@ -300,7 +303,7 @@ function Pressable(
if (android_rippleConfig != null) {
android_rippleConfig.onPressIn(event);
}
setPressed(true);
shouldUpdatePressed && setPressed(true);
if (onPressIn != null) {
onPressIn(event);
}
Expand All @@ -310,7 +313,7 @@ function Pressable(
if (android_rippleConfig != null) {
android_rippleConfig.onPressOut(event);
}
setPressed(false);
shouldUpdatePressed && setPressed(false);
if (onPressOut != null) {
onPressOut(event);
}
Expand All @@ -333,6 +336,7 @@ function Pressable(
onPressOut,
pressRetentionOffset,
setPressed,
shouldUpdatePressed,
unstable_pressDelay,
],
);
Expand Down

0 comments on commit cfa784c

Please sign in to comment.