ronantakizawa/codereview-bench huggingface dataset:
Repository: pmndrs/zustand
File: tests/ssr.test.tsx (TypeScript)

Code before:
import React, { useEffect } from 'react'
import { act, screen } from '@testing-library/react'
import { hydrateRoot } from 'react-dom/client'
import { renderToString } from 'react-dom/server'
import { describe, expect, it } from 'vitest'
import { create } from 'zustand'

const IS_REACT_18 = React.version.startsWith('18')

describe('ssr behavior with react 18', () => {
  interface BearStoreState {
    bears: number
  }

  interface BearStoreAction {
    increasePopulation: () => void
  }

  const initialState = { bears: 0 }
  const useBearStore = create<BearStoreState & BearStoreAction>((set) => ({
    ...initialState,
    increasePopulation: () => set(({ bears }) => ({ bears: bears + 1 })),
  }))

  function Counter() {
    const { bears, increasePopulation } = useBearStore(
      ({ bears, increasePopulation }) => ({
        bears,
        increasePopulation,
      })
    )

    useEffect(() => {

Review comment (suggestion):
We can skip any react version under 18

```suggestion
import React, { useEffect } from 'react'

if (!React.version.startsWith('18')) {
  describe.skip('skipping test on react version < 18', () => {})
  return
}

import { act, screen } from '@testing-library/react'
import { hydrateRoot } from 'react-dom/client'
import { renderToString } from 'react-dom/server'
import { describe, expect, it } from 'vitest'
import { create } from 'zustand'
```

Code after:
import React, { useEffect } from 'react'
import { act, screen } from '@testing-library/react'
import { renderToString } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { create } from 'zustand'

interface BearStoreState {
  bears: number
}

interface BearStoreAction {
  increasePopulation: () => void
}

const initialState = { bears: 0 }
const useBearStore = create<BearStoreState & BearStoreAction>((set) => ({
  ...initialState,
  increasePopulation: () => set(({ bears }) => ({ bears: bears + 1 })),
}))

function Counter() {
  const { bears, increasePopulation } = useBearStore(
    ({ bears, increasePopulation }) => ({
      bears,
      increasePopulation,
    })
  )

  useEffect(() => {
    increasePopulation()
  }, [increasePopulation])

  return <div>bears: {bears}</div>
Repository: pmndrs/zustand
File: tests/ssr.test.tsx (TypeScript)

Code before:
    )

    useEffect(() => {
      increasePopulation()
    }, [increasePopulation])

    return <div>bears: {bears}</div>
  }

  it('should handle different states between server and client correctly', async () => {
    const markup = renderToString(
      <React.Suspense fallback={<div>Loading...</div>}>
        <Counter />
      </React.Suspense>
    )

    const container = document.createElement('div')
    document.body.appendChild(container)
    container.innerHTML = markup

    expect(container.textContent).toContain('bears: 0')

    await act(async () => {
      // Using dynamic import for 'react-dom/client' as it’s not accessible in React versions below 18.
      // eslint-disable-next-line import/no-unresolved
      const { hydrateRoot } = await require('react-dom/client')
      hydrateRoot(
        container,
        <React.Suspense fallback={<div>Loading...</div>}>
          <Counter />
        </React.Suspense>
      )
    })

    const bearCountText = await screen.findByText('bears: 1')
    expect(bearCountText).not.toBeNull()
    document.body.removeChild(container)
  })
})


Review comment (suggestion):
Move to the top and use `vi.importActual` instead of require

```suggestion
```

Code after:
    increasePopulation()
  }, [increasePopulation])

  return <div>bears: {bears}</div>
}

describe.skipIf(!React.version.startsWith('18'))(
  'ssr behavior with react 18',
  () => {
    it('should handle different states between server and client correctly', async () => {
      const { hydrateRoot } = await vi.importActual<
        typeof import('react-dom/client')
      >('react-dom/client')

      const markup = renderToString(
        <React.Suspense fallback={<div>Loading...</div>}>
          <Counter />
        </React.Suspense>
      )

      const container = document.createElement('div')
      document.body.appendChild(container)
      container.innerHTML = markup

      expect(container.textContent).toContain('bears: 0')

      await act(async () => {
        hydrateRoot(
          container,
          <React.Suspense fallback={<div>Loading...</div>}>
            <Counter />
          </React.Suspense>
        )
      })

      const bearCountText = await screen.findByText('bears: 1')
      expect(bearCountText).not.toBeNull()
      document.body.removeChild(container)
    })
  }
)
Repository: pmndrs/zustand
File: tests/ssr.test.tsx (TypeScript)

Code before:
import React, { useEffect } from 'react'
import { act, screen } from '@testing-library/react'
import { renderToString } from 'react-dom/server'
import { describe, expect, it } from 'vitest'
import { create } from 'zustand'

const describeTest = React.version.startsWith('18') ? describe : describe.skip

describeTest('ssr behavior with react 18', () => {
  interface BearStoreState {
    bears: number
  }

  interface BearStoreAction {
    increasePopulation: () => void
  }

  const initialState = { bears: 0 }
  const useBearStore = create<BearStoreState & BearStoreAction>((set) => ({
    ...initialState,
    increasePopulation: () => set(({ bears }) => ({ bears: bears + 1 })),
  }))

  function Counter() {
    const { bears, increasePopulation } = useBearStore(
      ({ bears, increasePopulation }) => ({
        bears,
        increasePopulation,
      })
    )

    useEffect(() => {
      increasePopulation()
    }, [increasePopulation])


Review comment (suggestion):
```suggestion
  const { hydrateRoot } = await vi.importActual('react-dom/client')

  interface BearStoreState {
```

Code after:
import React, { useEffect } from 'react'
import { act, screen } from '@testing-library/react'
import { renderToString } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { create } from 'zustand'

interface BearStoreState {
  bears: number
}

interface BearStoreAction {
  increasePopulation: () => void
}

const initialState = { bears: 0 }
const useBearStore = create<BearStoreState & BearStoreAction>((set) => ({
  ...initialState,
  increasePopulation: () => set(({ bears }) => ({ bears: bears + 1 })),
}))

function Counter() {
  const { bears, increasePopulation } = useBearStore(
    ({ bears, increasePopulation }) => ({
      bears,
      increasePopulation,
    })
  )

  useEffect(() => {
    increasePopulation()
  }, [increasePopulation])

  return <div>bears: {bears}</div>
}
Repository: pmndrs/zustand
File: tests/ssr.test.tsx (TypeScript)

Code before:
import React, { useEffect } from 'react'
import { act, screen } from '@testing-library/react'
import { renderToString } from 'react-dom/server'
import { describe, expect, it } from 'vitest'
import { create } from 'zustand'

const describeTest = React.version.startsWith('18') ? describe : describe.skip

describeTest('ssr behavior with react 18', () => {
  interface BearStoreState {
    bears: number
  }

  interface BearStoreAction {
    increasePopulation: () => void
  }

  const initialState = { bears: 0 }
  const useBearStore = create<BearStoreState & BearStoreAction>((set) => ({
    ...initialState,
    increasePopulation: () => set(({ bears }) => ({ bears: bears + 1 })),
  }))

  function Counter() {
    const { bears, increasePopulation } = useBearStore(
      ({ bears, increasePopulation }) => ({
        bears,
        increasePopulation,
      })

Review comment (suggestion):
Add vi on imports

```suggestion
import { describe, expect, it, vi } from 'vitest'
```

Code after:
import React, { useEffect } from 'react'
import { act, screen } from '@testing-library/react'
import { renderToString } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { create } from 'zustand'

interface BearStoreState {
  bears: number
}

interface BearStoreAction {
  increasePopulation: () => void
}

const initialState = { bears: 0 }
const useBearStore = create<BearStoreState & BearStoreAction>((set) => ({
  ...initialState,
  increasePopulation: () => set(({ bears }) => ({ bears: bears + 1 })),
}))

function Counter() {
  const { bears, increasePopulation } = useBearStore(
    ({ bears, increasePopulation }) => ({
      bears,
      increasePopulation,
    })
  )

  useEffect(() => {
Repository: pmndrs/zustand
File: tests/ssr.test.tsx (TypeScript)

Code before:
import React, { useEffect } from 'react'
import { act, screen } from '@testing-library/react'
import { renderToString } from 'react-dom/server'
import { describe, expect, it } from 'vitest'
import { create } from 'zustand'

const describeTest = React.version.startsWith('18') ? describe : describe.skip

describeTest('ssr behavior with react 18', () => {
  interface BearStoreState {
    bears: number
  }

  interface BearStoreAction {
    increasePopulation: () => void
  }

  const initialState = { bears: 0 }
  const useBearStore = create<BearStoreState & BearStoreAction>((set) => ({
    ...initialState,
    increasePopulation: () => set(({ bears }) => ({ bears: bears + 1 })),
  }))

  function Counter() {
    const { bears, increasePopulation } = useBearStore(
      ({ bears, increasePopulation }) => ({
        bears,
        increasePopulation,
      })
    )

    useEffect(() => {
      increasePopulation()
    }, [increasePopulation])

Review comment (suggestion):
Let's use `describe.skipIf`

```suggestion
describe.skipIf(!React.version.startsWith('18'))('ssr behavior with react 18', () => {
```

Code after:
import React, { useEffect } from 'react'
import { act, screen } from '@testing-library/react'
import { renderToString } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { create } from 'zustand'

interface BearStoreState {
  bears: number
}

interface BearStoreAction {
  increasePopulation: () => void
}

const initialState = { bears: 0 }
const useBearStore = create<BearStoreState & BearStoreAction>((set) => ({
  ...initialState,
  increasePopulation: () => set(({ bears }) => ({ bears: bears + 1 })),
}))

function Counter() {
  const { bears, increasePopulation } = useBearStore(
    ({ bears, increasePopulation }) => ({
      bears,
      increasePopulation,
    })
  )

  useEffect(() => {
    increasePopulation()
  }, [increasePopulation])

  return <div>bears: {bears}</div>
}
Repository: pmndrs/zustand
File: tests/ssr.test.tsx (TypeScript)

Code before:
  const { bears, increasePopulation } = useBearStore(
    ({ bears, increasePopulation }) => ({
      bears,
      increasePopulation,
    })
  )

  useEffect(() => {
    increasePopulation()
  }, [increasePopulation])

  return <div>bears: {bears}</div>
}

describe.skipIf(!React.version.startsWith('18'))(
  'ssr behavior with react 18',
  async () => {
    it('should handle different states between server and client correctly', async () => {
      const {
        hydrateRoot,
      }: {
        hydrateRoot: (
          container: Element | Document,
          initialChildren: React.ReactNode
        ) => void
      } = await vi.importActual('react-dom/client')

      const markup = renderToString(
        <React.Suspense fallback={<div>Loading...</div>}>
          <Counter />
        </React.Suspense>
      )

      const container = document.createElement('div')
      document.body.appendChild(container)
      container.innerHTML = markup

      expect(container.textContent).toContain('bears: 0')

      await act(async () => {
        hydrateRoot(
          container,
          <React.Suspense fallback={<div>Loading...</div>}>
            <Counter />
          </React.Suspense>
        )
      })

      const bearCountText = await screen.findByText('bears: 1')
      expect(bearCountText).not.toBeNull()
      document.body.removeChild(container)

Review comment (suggestion):
```suggestion
      const { hydrateRoot } = await vi.importActual<typeof import('react-dom/client')>('react-dom/client')
```

Code after:
  const { bears, increasePopulation } = useBearStore(
    ({ bears, increasePopulation }) => ({
      bears,
      increasePopulation,
    })
  )

  useEffect(() => {
    increasePopulation()
  }, [increasePopulation])

  return <div>bears: {bears}</div>
}

describe.skipIf(!React.version.startsWith('18'))(
  'ssr behavior with react 18',
  () => {
    it('should handle different states between server and client correctly', async () => {
      const { hydrateRoot } = await vi.importActual<
        typeof import('react-dom/client')
      >('react-dom/client')

      const markup = renderToString(
        <React.Suspense fallback={<div>Loading...</div>}>
          <Counter />
        </React.Suspense>
      )

      const container = document.createElement('div')
      document.body.appendChild(container)
      container.innerHTML = markup

      expect(container.textContent).toContain('bears: 0')

      await act(async () => {
        hydrateRoot(
          container,
          <React.Suspense fallback={<div>Loading...</div>}>
            <Counter />
          </React.Suspense>
        )
      })

      const bearCountText = await screen.findByText('bears: 1')
      expect(bearCountText).not.toBeNull()
      document.body.removeChild(container)
    })
  }
)
Repository: pmndrs/zustand
File: src/shallow.ts (TypeScript)

Code before:
  return true
}

/**
 * @deprecated Use `import { shallow } from 'zustand/shallow'`
 */
export default ((objA, objB) => {
  if (import.meta.env?.MODE !== 'production') {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use `import { shallow } from 'zustand/shallow'`."
    )
  }
  return shallow(objA, objB)
}) as typeof shallow

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

  return useMemo(
    () => (state) => {
      const next = selector(state)
      return shallow(prev.current, next)
        ? (prev.current as U)
        : (prev.current = next)
    },
    [selector]
  )
}


Review comment (suggestion):
I don't think we need useMemo nor useCallback for this, because Zustand doesn't require stable selector.

Do you prefer `useRef`? I think we should use useMemo like https://github.com/pmndrs/zustand/discussions/1937#discussioncomment-6974554 , because React may prohibit updating ref during render in the future (L73 is usually not allowed).

Code after:
  return true
}

/**
 * @deprecated Use `import { shallow } from 'zustand/shallow'`
 */
export default ((objA, objB) => {
  if (import.meta.env?.MODE !== 'production') {
    console.warn(
      "[DEPRECATED] Default export is deprecated. Instead use `import { shallow } from 'zustand/shallow'`."
    )
  }
  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)
  }
}
Repository: pmndrs/zustand
File: tests/subscribe.test.tsx (TypeScript)

Code before:
import { describe, expect, it } from 'vitest'
import { create } from 'zustand'

describe('subscribe()', () => {
  it('should correctly have access to subscribe', () => {
    const { subscribe } = create(() => ({ value: 1 }))
    expect({ subscribe }).toMatchInlineSnapshot(`
    {
      "subscribe": [Function],
    }
  `)
  })
})


Review comment (suggestion):
Thanks.
I'd prefer `expect(typeof subscribe).toBe('function')` or something, instead of `toMachiInlineSnapshot`.

Code after:
import { describe, expect, it } from 'vitest'
import { create } from 'zustand'

describe('subscribe()', () => {
  it('should correctly have access to subscribe', () => {
    const { subscribe } = create(() => ({ value: 1 }))
    expect(typeof subscribe).toBe('function')
  })
})
Repository: pmndrs/zustand
File: tests/basic.test.tsx (TypeScript)

Code before:
    return (
      <>
        <div>inline: {inlineSelectorCallCount}</div>
        <div>static: {staticSelectorCallCount}</div>
      </>
    )
  }

  const { rerender, findByText } = render(
    <>
      <Component />
    </>,
  )
  await findByText('inline: 1')
  await findByText('static: 1')

  rerender(
    <>
      <Component />
    </>,
  )
  await findByText('inline: 2')
  await findByText('static: 1')

  act(() => setState({ a: 1, b: 1 }))
  await findByText('inline: 4')
  await findByText('static: 2')
})

it('ensures parent components subscribe before children', async () => {
  type State = {
    children: { [key: string]: { text: string } }
  }
  type Props = { id: string }
  const useBoundStore = create<State>(() => ({
    children: {
      '1': { text: 'child 1' },
      '2': { text: 'child 2' },
    },
  }))
  const api = useBoundStore

  function changeState() {
    api.setState({
      children: {
        '3': { text: 'child 3' },
      },
    })
  }

  function Child({ id }: Props) {

Review comment (suggestion):
This behavior (inline selector optimization) isn't supported in v5. Use `zustand/traditional`.

Code after:
        <div>static: {staticSelectorCallCount}</div>
      </>
    )
  }

  const { rerender, findByText } = render(
    <>
      <Component />
    </>,
  )
  await findByText('static: 1')

  rerender(
    <>
      <Component />
    </>,
  )
  await findByText('static: 1')

  act(() => setState({ a: 1, b: 1 }))
  await findByText('static: 2')
})

it('only calls selectors when necessary (traditional)', async () => {
  type State = { a: number; b: number }
  const useBoundStore = createWithEqualityFn<State>(() => ({ a: 0, b: 0 }))
  const { setState } = useBoundStore
  let inlineSelectorCallCount = 0
  let staticSelectorCallCount = 0

  function staticSelector(s: State) {
    staticSelectorCallCount++
    return s.a
  }

  function Component() {
    useBoundStore((s) => (inlineSelectorCallCount++, s.b))
    useBoundStore(staticSelector)
    return (
      <>
        <div>inline: {inlineSelectorCallCount}</div>
        <div>static: {staticSelectorCallCount}</div>
      </>
    )
  }

  const { rerender, findByText } = render(
    <>
      <Component />
    </>,
  )
Repository: pmndrs/zustand
File: src/middleware/immer.ts (TypeScript)

Code before:
        : T extends [unknown, unknown?, ...infer A]
          ? A
          : T extends [unknown?, unknown?, ...infer A]
            ? A
            : never

type SetStateType<T extends unknown[]> = Exclude<T[0], (...args: any[]) => any>

type WithImmer<S> = Write<S, StoreImmer<S>>

type StoreImmer<S> = S extends {
  setState: infer SetState
}
  ? SetState extends {
      (...a: infer A1): infer Sr1
      (...a: infer A2): infer Sr2
    }
    ? {
        setState(
          nextStateOrUpdater:
            | SetStateType<A2>
            | Partial<SetStateType<A2>>
            | ((state: Draft<SetStateType<A2>>) => void),
          shouldReplace?: false,
          ...a: SkipTwo<A1>
        ): Sr1
        setState(
          nextStateOrUpdater:
            | SetStateType<A2>
            | ((state: Draft<SetStateType<A2>>) => void),
          shouldReplace: true,
          ...a: SkipTwo<A2>
        ): Sr2
      }
    : never
  : never

type ImmerImpl = <T>(
  storeInitializer: StateCreator<T, [], []>,
) => StateCreator<T, [], []>

const immerImpl: ImmerImpl = (initializer) => (set, get, store) => {
  type T = ReturnType<typeof initializer>

  store.setState = (updater, replace, ...a) => {
    const nextState = (
      typeof updater === 'function' ? produce(updater as any) : updater
    ) as ((s: T) => T) | T | Partial<T>

    return set(nextState, replace as any, ...a)
  }

Review comment (suggestion):
Can we add a comment that ideally we want to infer types from `A1`.

Code after:
        : T extends [unknown, unknown?, ...infer A]
          ? A
          : T extends [unknown?, unknown?, ...infer A]
            ? A
            : never

type SetStateType<T extends unknown[]> = Exclude<T[0], (...args: any[]) => any>

type WithImmer<S> = Write<S, StoreImmer<S>>

type StoreImmer<S> = S extends {
  setState: infer SetState
}
  ? SetState extends {
      (...a: infer A1): infer Sr1
      (...a: infer A2): infer Sr2
    }
    ? {
        // Ideally, we would want to infer the `nextStateOrUpdater` `T` type from the
        // `A1` type, but this is infeasible since it is an intersection with
        // a partial type.
        setState(
          nextStateOrUpdater:
            | SetStateType<A2>
            | Partial<SetStateType<A2>>
            | ((state: Draft<SetStateType<A2>>) => void),
          shouldReplace?: false,
          ...a: SkipTwo<A1>
        ): Sr1
        setState(
          nextStateOrUpdater:
            | SetStateType<A2>
            | ((state: Draft<SetStateType<A2>>) => void),
          shouldReplace: true,
          ...a: SkipTwo<A2>
        ): Sr2
      }
    : never
  : never

type ImmerImpl = <T>(
  storeInitializer: StateCreator<T, [], []>,
) => StateCreator<T, [], []>

const immerImpl: ImmerImpl = (initializer) => (set, get, store) => {
  type T = ReturnType<typeof initializer>

  store.setState = (updater, replace, ...a) => {
    const nextState = (
      typeof updater === 'function' ? produce(updater as any) : updater
    ) as ((s: T) => T) | T | Partial<T>