Skip to content
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

fix(shallow): Extract shallow vanilla and react #2097

Merged
merged 19 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
2 changes: 1 addition & 1 deletion docs/guides/prevent-rerenders-with-use-shallow.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ We can fix that using `useShallow`!

```js
import { create } from 'zustand'
import { useShallow } from 'zustand/shallow'
import { useShallow } from 'zustand/shallow/react'

const useMeals = create(() => ({
papaBear: 'large porridge-pot',
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ If you want to construct a single object with multiple state-picks inside, simil

```jsx
import { create } from 'zustand'
import { useShallow } from 'zustand/shallow'
import { useShallow } from 'zustand/shallow/react'

const useBearStore = create((set) => ({
bears: 0,
Expand Down
13 changes: 0 additions & 13 deletions src/shallow.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { useRef } from 'react'

export function shallow<T>(objA: T, objB: T) {
if (Object.is(objA, objB)) {
return true
Expand Down Expand Up @@ -61,14 +59,3 @@ export default ((objA, objB) => {
}
return shallow(objA, objB)
}) as typeof shallow

export function useShallow<S, U>(selector: (state: S) => U): (state: S) => U {
const prev = useRef<U>()

return (state) => {
const next = selector(state)
return shallow(prev.current, next)
? (prev.current as U)
: (prev.current = next)
}
}
13 changes: 13 additions & 0 deletions src/shallow/react.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useRef } from 'react'
import { shallow } from '../shallow.ts'

export function useShallow<S, U>(selector: (state: S) => U): (state: S) => U {
const prev = useRef<U>()

return (state) => {
const next = selector(state)
return shallow(prev.current, next)
? (prev.current as U)
: (prev.current = next)
}
}
106 changes: 2 additions & 104 deletions tests/shallow.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,99 +2,8 @@ import { useState } from 'react'
import { act, fireEvent, render } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { create } from 'zustand'
import { shallow, useShallow } from 'zustand/shallow'

describe('shallow', () => {
it('compares primitive values', () => {
expect(shallow(true, true)).toBe(true)
expect(shallow(true, false)).toBe(false)

expect(shallow(1, 1)).toBe(true)
expect(shallow(1, 2)).toBe(false)

expect(shallow('zustand', 'zustand')).toBe(true)
expect(shallow('zustand', 'redux')).toBe(false)
})

it('compares objects', () => {
expect(shallow({ foo: 'bar', asd: 123 }, { foo: 'bar', asd: 123 })).toBe(
true
)

expect(
shallow({ foo: 'bar', asd: 123 }, { foo: 'bar', foobar: true })
).toBe(false)

expect(
shallow({ foo: 'bar', asd: 123 }, { foo: 'bar', asd: 123, foobar: true })
).toBe(false)
})

it('compares arrays', () => {
expect(shallow([1, 2, 3], [1, 2, 3])).toBe(true)

expect(shallow([1, 2, 3], [2, 3, 4])).toBe(false)

expect(
shallow([{ foo: 'bar' }, { asd: 123 }], [{ foo: 'bar' }, { asd: 123 }])
).toBe(false)

expect(shallow([{ foo: 'bar' }], [{ foo: 'bar', asd: 123 }])).toBe(false)
})

it('compares Maps', () => {
function createMap<T extends object>(obj: T) {
return new Map(Object.entries(obj))
}

expect(
shallow(
createMap({ foo: 'bar', asd: 123 }),
createMap({ foo: 'bar', asd: 123 })
)
).toBe(true)

expect(
shallow(
createMap({ foo: 'bar', asd: 123 }),
createMap({ foo: 'bar', foobar: true })
)
).toBe(false)

expect(
shallow(
createMap({ foo: 'bar', asd: 123 }),
createMap({ foo: 'bar', asd: 123, foobar: true })
)
).toBe(false)
})

it('compares Sets', () => {
expect(shallow(new Set(['bar', 123]), new Set(['bar', 123]))).toBe(true)

expect(shallow(new Set(['bar', 123]), new Set(['bar', 2]))).toBe(false)

expect(shallow(new Set(['bar', 123]), new Set(['bar', 123, true]))).toBe(
false
)
})

it('compares functions', () => {
function firstFnCompare() {
return { foo: 'bar' }
}

function secondFnCompare() {
return { foo: 'bar' }
}

expect(shallow(firstFnCompare, firstFnCompare)).toBe(true)

expect(shallow(secondFnCompare, secondFnCompare)).toBe(true)

expect(shallow(firstFnCompare, secondFnCompare)).toBe(false)
})
})
import { shallow } from 'zustand/shallow'
import { useShallow } from 'zustand/shallow/react'

describe('types', () => {
it('works with useBoundStore and array selector (#1107)', () => {
Expand Down Expand Up @@ -123,17 +32,6 @@ describe('types', () => {
})
})

describe('unsupported cases', () => {
it('date', () => {
expect(
shallow(
new Date('2022-07-19T00:00:00.000Z'),
new Date('2022-07-20T00:00:00.000Z')
)
).not.toBe(false)
})
})

describe('useShallow', () => {
const testUseShallowSimpleCallback =
vi.fn<[{ selectorOutput: string[]; useShallowOutput: string[] }]>()
Expand Down
136 changes: 136 additions & 0 deletions tests/vanilla/basic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { afterEach, expect, it, vi } from 'vitest'
import { createStore } from 'zustand/vanilla'
import type { StoreApi } from 'zustand/vanilla'

// To avoid include react deps on vanilla version
vi.mock('react', () => ({}))

const consoleError = console.error
afterEach(() => {
console.error = consoleError
})

it('create a store', () => {
let params
const result = createStore((...args) => {
params = args
return { value: null }
})
expect({ params, result }).toMatchInlineSnapshot(`
{
"params": [
[Function],
[Function],
{
"destroy": [Function],
"getState": [Function],
"setState": [Function],
"subscribe": [Function],
},
],
"result": {
"destroy": [Function],
"getState": [Function],
"setState": [Function],
"subscribe": [Function],
},
}
`)
})

type CounterState = {
count: number
inc: () => void
}

it('uses the store', async () => {
const store = createStore<CounterState>((set) => ({
count: 0,
inc: () => set((state) => ({ count: state.count + 1 })),
}))
store.getState().inc()

expect(store.getState().count).toBe(1)
})

it('can get the store', async () => {
type State = {
value: number
getState1: () => State
getState2: () => State
}

const store = createStore<State>((_, get) => ({
value: 1,
getState1: () => get(),
getState2: (): State => store.getState(),
}))

expect(store.getState().getState1().value).toBe(1)
expect(store.getState().getState2().value).toBe(1)
})

it('can set the store', async () => {
type State = {
value: number
setState1: StoreApi<State>['setState']
setState2: StoreApi<State>['setState']
}

const store = createStore<State>((set) => ({
value: 1,
setState1: (v) => set(v),
setState2: (v): void => store.setState(v),
}))

store.getState().setState1({ value: 2 })
expect(store.getState().value).toBe(2)
store.getState().setState2({ value: 3 })
expect(store.getState().value).toBe(3)
})

it('both NaN should not update', () => {
const store = createStore<number>(() => NaN)
const fn = vi.fn()

store.subscribe(fn)
store.setState(NaN)

expect(fn).not.toBeCalled()
})

it('can set the store without merging', () => {
const { setState, getState } = createStore<{ a: number } | { b: number }>(
(_set) => ({
a: 1,
})
)

// Should override the state instead of merging.
setState({ b: 2 }, true)

expect(getState()).toEqual({ b: 2 })
})

it('works with non-object state', () => {
const store = createStore<number>(() => 1)
const inc = () => store.setState((c) => c + 1)

inc()

expect(store.getState()).toBe(2)
})

it('can destroy the store', () => {
const { destroy, getState, setState, subscribe } = createStore(() => ({
value: 1,
}))

subscribe(() => {
throw new Error('did not clear listener on destroy')
})
destroy()

setState({ value: 2 })
expect(getState().value).toEqual(2)
})
Loading
Loading