Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions apps/TesterIntegrated/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect } from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
import { useBrownieStore } from '@callstack/brownie';
import { useBrownieStore, shallow } from '@callstack/brownie';
import {
createNativeStackNavigator,
type NativeStackScreenProps,
Expand Down Expand Up @@ -34,7 +34,11 @@ const theme = getRandomTheme();

function HomeScreen({ navigation, route }: HomeScreenProps) {
const colors = route.params?.theme || theme;
const [state, setState] = useBrownieStore('BrownfieldStore');
const [counter, setState] = useBrownieStore(
'BrownfieldStore',
(s) => s.counter
);
const [user] = useBrownieStore('BrownfieldStore', (s) => s.user, shallow);

useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
Expand All @@ -51,12 +55,12 @@ function HomeScreen({ navigation, route }: HomeScreenProps) {
</Text>

<Text style={[styles.text, { color: colors.secondary }]}>
Count: {state.counter}
Count: {counter}
</Text>

<TextInput
style={styles.input}
value={state.user.name}
value={user.name}
onChangeText={(text) =>
setState((prev) => ({ user: { ...prev.user, name: text } }))
}
Expand Down
43 changes: 42 additions & 1 deletion packages/brownie/ArchitectureOverview.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ packages/brownie/
### React Hook

```ts
// useState-like API for store access
// Full state (useState-like API)
const [state, setState] = useBrownieStore('BrownfieldStore');

// Read state
Expand All @@ -321,6 +321,47 @@ setState({ counter: state.counter + 1 });
setState((prev) => ({ counter: prev.counter + 1 }));
```

### Selectors

Selectors allow subscribing to a slice of state, reducing unnecessary re-renders:

```ts
import { useBrownieStore, shallow } from '@callstack/brownie';

// Select primitive - re-renders only when counter changes
const [counter, setState] = useBrownieStore(
Comment thread
okwasniewski marked this conversation as resolved.
Outdated
'BrownfieldStore',
(s) => s.counter
);

// Select object with shallow equality
const [user, setState] = useBrownieStore(
'BrownfieldStore',
(s) => s.user,
shallow
);
```

**How it works:**

1. Native side notifies JS on every state change (full state)
2. Each `useBrownieStore` subscribes to full state but extracts only what it needs via selector
3. `useSyncExternalStoreWithSelector` compares previous vs new selected value - skips re-render if equal

**Equality functions:**

| Equality | Use case |
| ----------- | ------------------------------------------------ |
| `Object.is` | Default. Works for primitives (`s => s.counter`) |
| `shallow` | Objects/arrays - compares top-level props only |
| Custom `fn` | Deep nesting or complex comparison logic |

**Why `shallow` is needed:**

Without it, selecting an object (`s => s.user`) returns a new reference every time (JS creates new object on each native→JS crossing), causing re-renders even if contents are identical. `shallow` compares top-level properties to detect actual changes.

**Limitation:** `shallow` only goes one level deep. For nested objects like `{ user: { profile: { name } } }`, if `profile` object changes identity but has same contents, shallow won't catch it. Use more granular selectors or a custom `equalityFn` for deep nesting.

### Core Functions

```ts
Expand Down
49 changes: 37 additions & 12 deletions packages/brownie/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,41 @@
/** @type {import('jest').Config} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/scripts/**/*.test.ts'],
moduleFileExtensions: ['ts', 'js'],
clearMocks: true,
transform: {
'^.+\\.ts$': [
'ts-jest',
{
tsconfig: '<rootDir>/scripts/__tests__/tsconfig.json',
projects: [
{
displayName: 'scripts',
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/scripts/**/*.test.ts'],
moduleFileExtensions: ['ts', 'js'],
clearMocks: true,
transform: {
'^.+\\.ts$': [
'ts-jest',
Comment thread
okwasniewski marked this conversation as resolved.
Outdated
{
tsconfig: '<rootDir>/scripts/__tests__/tsconfig.json',
},
],
},
],
},
},
{
displayName: 'src',
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/src/**/*.test.ts'],
moduleFileExtensions: ['ts', 'js'],
clearMocks: true,
moduleNameMapper: {
'^./NativeBrownieModule$':
'<rootDir>/src/__tests__/__mocks__/NativeBrownieModule.ts',
},
transform: {
'^.+\\.ts$': [
'ts-jest',
{
tsconfig: '<rootDir>/src/__tests__/tsconfig.json',
},
],
},
},
],
};
4 changes: 3 additions & 1 deletion packages/brownie/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@
"dependencies": {
"quicktype-core": "^23.0.170",
"quicktype-typescript-input": "^23.0.170",
"ts-morph": "^25.0.0"
"ts-morph": "^25.0.0",
"use-sync-external-store": "^1.4.0"
Comment thread
okwasniewski marked this conversation as resolved.
Outdated
},
"devDependencies": {
"@babel/core": "^7.25.2",
Expand All @@ -74,6 +75,7 @@
"@types/jest": "^29.5.14",
"@types/node": "^22.0.0",
"@types/react": "^19.1.1",
"@types/use-sync-external-store": "^0.0.6",
"jest": "^29.7.0",
"react": "19.1.1",
"react-native": "0.82.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
nativeStoreDidChange: jest.fn(),
};
96 changes: 96 additions & 0 deletions packages/brownie/src/__tests__/shallow.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { shallow } from '../shallow';

describe('shallow', () => {
it('returns true for identical primitives', () => {
expect(shallow(1, 1)).toBe(true);
expect(shallow('a', 'a')).toBe(true);
expect(shallow(true, true)).toBe(true);
expect(shallow(null, null)).toBe(true);
expect(shallow(undefined, undefined)).toBe(true);
});

it('returns false for different primitives', () => {
expect(shallow(1, 2)).toBe(false);
expect(shallow('a', 'b')).toBe(false);
expect(shallow(true, false)).toBe(false);
});

it('returns true for same object reference', () => {
const obj = { a: 1 };
expect(shallow(obj, obj)).toBe(true);
});

it('returns true for objects with same top-level values', () => {
expect(shallow({ a: 1, b: 2 }, { a: 1, b: 2 })).toBe(true);
});

it('returns false for objects with different top-level values', () => {
expect(shallow({ a: 1 }, { a: 2 })).toBe(false);
expect(shallow({ a: 1 }, { a: 1, b: 2 })).toBe(false);
});

it('does not deeply compare nested objects', () => {
const nested1 = { a: { b: 1 } };
const nested2 = { a: { b: 1 } };
expect(shallow(nested1, nested2)).toBe(false);
});

it('returns true for same nested object reference', () => {
const inner = { b: 1 };
expect(shallow({ a: inner }, { a: inner })).toBe(true);
});

it('returns true for equal arrays', () => {
expect(shallow([1, 2, 3], [1, 2, 3])).toBe(true);
});

it('returns false for arrays with different values', () => {
expect(shallow([1, 2], [1, 3])).toBe(false);
expect(shallow([1, 2], [1, 2, 3])).toBe(false);
});

it('returns true for equal Maps', () => {
const mapA = new Map([
['a', 1],
['b', 2],
]);
const mapB = new Map([
['a', 1],
['b', 2],
]);
expect(shallow(mapA, mapB)).toBe(true);
});

it('returns false for Maps with different values', () => {
const mapA = new Map([['a', 1]]);
const mapB = new Map([['a', 2]]);
expect(shallow(mapA, mapB)).toBe(false);
});

it('returns true for equal Sets', () => {
const setA = new Set([1, 2, 3]);
const setB = new Set([1, 2, 3]);
expect(shallow(setA, setB)).toBe(true);
});

it('returns false for Sets with different values', () => {
const setA = new Set([1, 2]);
const setB = new Set([1, 3]);
expect(shallow(setA, setB)).toBe(false);
});

it('returns false for different prototypes', () => {
class A {
x = 1;
}
class B {
x = 1;
}
expect(shallow(new A(), new B())).toBe(false);
});

it('returns false when comparing object to null', () => {
expect(shallow({ a: 1 }, null)).toBe(false);
expect(shallow(null, { a: 1 })).toBe(false);
});
});
6 changes: 6 additions & 0 deletions packages/brownie/src/__tests__/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": "../../../../tsconfig",
"compilerOptions": {
"verbatimModuleSyntax": false
}
}
45 changes: 40 additions & 5 deletions packages/brownie/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useSyncExternalStore } from 'react';
import { useCallback, useDebugValue } from 'react';
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';
import BrownieModule from './NativeBrownieModule';

/**
Expand Down Expand Up @@ -95,23 +96,57 @@ export function setState<K extends keyof BrownieStores>(
}
}

const identity = <T>(x: T): T => x;

export { shallow } from './shallow';

/**
* React hook for subscribing to a native store.
* React hook for subscribing to a native store with optional selector.
* @param key Store key registered in StoreManager
* @returns Tuple of [state, setState] for the store
*/
export function useBrownieStore<K extends keyof BrownieStores>(
key: K
): [BrownieStores[K], (action: SetStateAction<BrownieStores[K]>) => void] {
): [BrownieStores[K], (action: SetStateAction<BrownieStores[K]>) => void];

/**
* React hook for subscribing to a native store with selector.
* @param key Store key registered in StoreManager
* @param selector Function to select a slice of state
* @param equalityFn Optional equality function for comparing selected values
* @returns Tuple of [selectedState, setState] for the store
*/
export function useBrownieStore<K extends keyof BrownieStores, U>(
key: K,
selector: (state: BrownieStores[K]) => U,
equalityFn?: (a: U, b: U) => boolean
): [U, (action: SetStateAction<BrownieStores[K]>) => void];

export function useBrownieStore<K extends keyof BrownieStores, U>(
key: K,
selector?: (state: BrownieStores[K]) => U,
equalityFn?: (a: U, b: U) => boolean
): [U | BrownieStores[K], (action: SetStateAction<BrownieStores[K]>) => void] {
const sub = useCallback(
(listener: () => void) => subscribe(key, listener),
[key]
);
const snap = useCallback(() => getSnapshot(key), [key]);
const state = useSyncExternalStore(sub, snap, snap);

const slice = useSyncExternalStoreWithSelector(
sub,
snap,
snap,
selector ?? (identity as (state: BrownieStores[K]) => U),
equalityFn
);

useDebugValue(slice);

const boundSetState = useCallback(
(action: SetStateAction<BrownieStores[K]>) => setState(key, action),
[key]
);
return [state, boundSetState];

return [slice, boundSetState];
}
Loading