refactor: improve useColorScheme subscription efficiency (#38001)

Summary:
motivation: re-rendering `useColorScheme()` hook with what is on the main branch means there is a subscribe + unsubscribe dance happening.

related docs: https://react.dev/reference/react/useSyncExternalStore#my-subscribe-function-gets-called-after-every-re-render

## Changelog:

<!-- Help reviewers and the release process by writing your own changelog entry.

Pick one each for the category and type tags:

[INTERNAL] [CHANGED] - improve useColorScheme subscription efficiency

For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests

Pull Request resolved: https://github.com/facebook/react-native/pull/38001

Test Plan: tested locally in an app

Reviewed By: rshest

Differential Revision: D49008053

Pulled By: javache

fbshipit-source-id: f8a9fc8950277e2bae8bd8774bf21312a67d46d5
This commit is contained in:
Vojtech Novak
2023-09-06 06:24:03 -07:00
committed by Facebook GitHub Bot
parent 7ac58772b1
commit b08d0df95f
@@ -15,12 +15,11 @@ import type {ColorSchemeName} from './NativeAppearance';
import Appearance from './Appearance';
import {useSyncExternalStore} from 'react';
const subscribe = (onStoreChange: () => void) => {
const appearanceSubscription = Appearance.addChangeListener(onStoreChange);
return () => appearanceSubscription.remove();
};
export default function useColorScheme(): ?ColorSchemeName {
return useSyncExternalStore(
callback => {
const appearanceSubscription = Appearance.addChangeListener(callback);
return () => appearanceSubscription.remove();
},
() => Appearance.getColorScheme(),
);
return useSyncExternalStore(subscribe, Appearance.getColorScheme);
}