Skip to content

Commit

Permalink
refactor: improve useColorScheme subscription efficiency (#38001)
Browse files Browse the repository at this point in the history
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: #38001

Test Plan: tested locally in an app

Reviewed By: rshest

Differential Revision: D49008053

Pulled By: javache

fbshipit-source-id: f8a9fc8950277e2bae8bd8774bf21312a67d46d5
  • Loading branch information
vonovak authored and facebook-github-bot committed Sep 6, 2023
1 parent 7ac5877 commit b08d0df
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions packages/react-native/Libraries/Utilities/useColorScheme.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit b08d0df

Please sign in to comment.