Skip to content

perf: improve performance of useSelector by moving to shallowRef #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 20, 2024
Merged
Changes from all commits
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
14 changes: 7 additions & 7 deletions packages/vue-redux/src/compositions/use-selector.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { readonly, ref, toRaw, watch } from 'vue'
import { shallowReadonly, shallowRef, toRaw, watch } from 'vue'
import { ContextKey } from '../provider/context'
import {
createReduxContextComposition,
useReduxContext as useDefaultReduxContext,
} from './use-redux-context'
import type { DeepReadonly, InjectionKey, Ref, UnwrapRef } from 'vue'
import type { InjectionKey, ShallowRef } from 'vue'
import type { EqualityFn } from '../types'
import type { VueReduxContextValue } from '../provider/context'

Expand Down Expand Up @@ -41,7 +41,7 @@ export interface UseSelector<StateType = unknown> {
<TState extends StateType = StateType, Selected = unknown>(
selector: (state: TState) => Selected,
equalityFnOrOptions?: EqualityFn<Selected> | UseSelectorOptions<Selected>,
): Readonly<Ref<DeepReadonly<UnwrapRef<Selected>>>>
): Readonly<ShallowRef<Selected>>

/**
* Creates a "pre-typed" version of {@linkcode useSelector useSelector}
Expand Down Expand Up @@ -83,7 +83,7 @@ export function createSelectorComposition(
equalityFnOrOptions:
| EqualityFn<Selected>
| UseSelectorOptions<Selected> = {},
): Readonly<Ref<DeepReadonly<UnwrapRef<Selected>>>> => {
): Readonly<ShallowRef<Selected>> => {
const { equalityFn = refEquality } =
typeof equalityFnOrOptions === 'function'
? { equalityFn: equalityFnOrOptions }
Expand All @@ -93,7 +93,7 @@ export function createSelectorComposition(

// TODO: Introduce wrappedSelector for debuggability

const selectedState = ref(selector(store.getState() as TState))
const selectedState = shallowRef(selector(store.getState() as TState))

watch(
() => store,
Expand All @@ -104,7 +104,7 @@ export function createSelectorComposition(
return
}

selectedState.value = data as UnwrapRef<Selected>
selectedState.value = data
})

onCleanup(() => {
Expand All @@ -116,7 +116,7 @@ export function createSelectorComposition(
},
)

return readonly(selectedState)
return shallowReadonly(selectedState)
}

Object.assign(useSelector, {
Expand Down
Loading