useBoundStoreWithEqualityFn in Zustand’s source code explained.

useBoundStoreWithEqualityFn in Zustand’s source code explained.

In this article, we will understand how the useBoundStoreWithEqualityFn function is used in Zustand’s source code.

The above code is picked from https://github.com/pmndrs/zustand/blob/main/src/traditional.ts#L80

useBoundStoreWithEqualityFn is called in createWithEqualityFnImplfunction and returns another function named useStoreWithEqualityFn.

Let’s look at what’s in useStoreWithEqualityFn.

// Pulled from https://github.com/pmndrs/zustand/blob/main/src/traditional.ts#L80
export function useStoreWithEqualityFn<TState, StateSlice>(
  api: ReadonlyStoreApi<TState>,
  selector: (state: TState) => StateSlice = identity as any,
  equalityFn?: (a: StateSlice, b: StateSlice) => boolean,
) {
  const slice = useSyncExternalStoreWithSelector(
    api.subscribe,
    api.getState,
    api.getInitialState,
    selector,
    equalityFn,
  )
  useDebugValue(slice)
  return slice
}

useSyncExternalStore is a React Hook that lets you subscribe to an external store and useSyncExternalStoreWithSelector is imported as shown below:

import useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector'

slice returned by this function, useStoreWithEqualityFn is further used in createWithEqualityFnImpl .

const useBoundStoreWithEqualityFn: any = (
  selector?: any,
  equalityFn = defaultEqualityFn,
) => useStoreWithEqualityFn(api, selector, equalityFn)

Object.assign(useBoundStoreWithEqualityFn, api)

return useBoundStoreWithEqualityFn

Object.assign updates the slice returned by useBoundStoreWithEqualityFn with the “api”.

The screenshot below demonstrates with an example how Object.assign does the update

and finally useBoundStoreWithEqualityFn is returned by createWithEqualityFnImpl.

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on an interesting project. Send me an email at ramu.narasinga@gmail.com

My Github - https://github.com/ramu-narasinga My website - https://ramunarasinga.com My Youtube channel - https://www.youtube.com/@thinkthroo Learning platform - https://thinkthroo.com Codebase Architecture - https://app.thinkthroo.com/architecture Best practices - https://app.thinkthroo.com/best-practices Production-grade projects - https://app.thinkthroo.com/production-grade-projects

References:

  1. https://github.com/search?q=useBoundStore&type=code

  2. https://github.com/churichard/notabase