Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: pmndrs/zustand
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v4.3.7
Choose a base ref
...
head repository: pmndrs/zustand
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v4.3.8
Choose a head ref
  • 19 commits
  • 49 files changed
  • 15 contributors

Commits on Apr 7, 2023

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    2970ed2 View commit details
  2. fixes #1735 (#1737)

    JacobWeisenburger authored Apr 7, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f94ad23 View commit details
  3. fix(docs): update testing doc (#1739)

    * Update formatting
    
    * Update testing doc
    
    * Fix formatting
    
    * Minor changes
    
    * Update testing doc
    dbritto-dev authored Apr 7, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    4c2c482 View commit details

Commits on Apr 8, 2023

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    6d47b60 View commit details

Commits on Apr 12, 2023

  1. feature(demo): update demo to support copying typescript code (#1740)

    * Update demo
    
    * Minor changes
    
    * Minor changes
    
    * Minor changes
    
    * Minor changes
    
    * Minor changes
    
    * Minor changes
    
    * Minor changes
    dbritto-dev authored Apr 12, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    6b716fb View commit details

Commits on Apr 14, 2023

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    7cdb5f5 View commit details

Commits on Apr 17, 2023

  1. Fix document details (#1752)

    export const useBoundStore = create((set) => ({
      count: 0,
      text: 'hello',
      inc: () => set((state) => ({ count: state.count + 1 })),
      setText: (text) => set({ text }),
    })
    
    example on this page is missing a trailing parenthesis
    zc627788 authored Apr 17, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    df38aa8 View commit details

Commits on Apr 18, 2023

  1. docs: fix document error of persist with hydration (#1758)

    * docs: fix document error of persist with hydration
    
    * Update persisting-store-data.md
    
    * Apply suggestions from code review
    
    Co-authored-by: Blazej Sewera <code@sewera.dev>
    
    * Update persisting-store-data.md
    
    ---------
    
    Co-authored-by: Blazej Sewera <code@sewera.dev>
    arvinxx and sewera authored Apr 18, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    a999f7a View commit details

Commits on Apr 22, 2023

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    da45038 View commit details

Commits on Apr 24, 2023

  1. Update Transient in recipes to match Readme (#1764)

    * Update Transient in recipes to match Readme
    
    
    
    https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes
    
    * Update docs/recipes/recipes.mdx
    
    Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
    
    * update to useScratchStore
    
    ---------
    
    Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
    timarney and dai-shi authored Apr 24, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    513b222 View commit details

Commits on Apr 28, 2023

  1. docs(typescript): fix bounded use store example (#1779)

    * test: changer
    
    * docs: fix abstract bounded store hook TS example
    
    Fixes type issues due to optional arg:
    #1564 (comment)
    
    * fix: pr feedback
    dannobytes authored Apr 28, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    e71e313 View commit details

Commits on Apr 30, 2023

  1. Add code heading in comparison with Zustand and Redux (#1777)

    * Add code heading
    
    * Add newline
    
    Co-authored-by: Danilo Britto <dbritto.dev@gmail.com>
    
    ---------
    
    Co-authored-by: Danilo Britto <dbritto.dev@gmail.com>
    BLooDBRothER and dbritto-dev authored Apr 30, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    22db001 View commit details

Commits on May 1, 2023

  1. chore: add extentsion in imports (#1678)

    * chore: add extentsion in imports
    
    * fix github workflow
    
    * revert for zustand/context
    
    * do not patch :)
    
    * fix workflow file
    
    * update ts 5
    
    * patch tsconfig
    
    * use old typescript for react 16
    
    * downlevel-dts to 3.8
    
    * Revert "downlevel-dts to 3.8"
    
    This reverts commit d03e526.
    
    * patch workflow file
    
    * patch for react 16
    
    * remove ts3.4 in workflow
    
    * skipLibChecks
    
    * revert changes in test-multiple-versions.yml
    
    * fix sed
    
    * wip: add allowJs
    
    * Revert "wip: add allowJs"
    
    This reverts commit fca34d7.
    
    * use ts 495
    
    * useESM false
    
    * Revert "useESM false"
    
    This reverts commit 07a91d8.
    
    * no coverage
    
    * no coverage 2
    
    * no coverage 3
    
    * wip
    
    * disable transform
    
    * revert a change
    
    * revert changes
    
    * test: try ignoring tests with dynamic imports
    
    * test: skip tests that require/tests modules in isolation
    
    * test: remove dynamic import
    
    * run skipped tests on CI
    
    * test: add new devtools imports to ci-only tests
    
    * revert CI-ONLY-* hack
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * wip: workaround for react 16
    
    * CI-MATRIX- for devtools CI hacks
    
    * test: add env variable to test multiple builds workflow
    
    * hack await import
    
    * hack await import for another one
    
    * wip: experimenting workflow file
    
    * wip: experimenting workflow file
    
    * wip: experimenting workflow file
    
    * use different env name
    
    * wip: experimenting workflow file
    
    * do not use two envs
    
    * revert to NODE_ENV
    
    ---------
    
    Co-authored-by: Arjun <14841132+arjunvegda@users.noreply.github.com>
    dai-shi and arjunvegda authored May 1, 2023
    2

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f37530f View commit details
  2. fix: workflow file syntax error (#1786)

    * fix workflow file format
    
    * does it change?
    
    * hope this works
    
    * fix syntax
    dai-shi authored May 1, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    1808bf4 View commit details

Commits on May 4, 2023

  1. feat(middleware/persist): improve createJSONStorage for Maps (#1763)

    * feat: add support for Maps to persist middleware
    
    * refactor: change createJsonStorage to accept custom reviver/replacer
    
    * refactor: map support code review
    lauhon authored May 4, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    630ba1a View commit details
  2. chore(tests): migrate to vitest (#1753)

    * test: migrate to vitest
    
    * test: try #1 remove CI-MATRIX tags
    
    * test: try 2 remove import/require replace
    
    * chore: remove unused scripts/assignments
    
    * chore(test-multiple-builds.yml): remove import/require replace script
    
    * fix merging main
    
    ---------
    
    Co-authored-by: daishi <daishi@axlight.com>
    arjunvegda and dai-shi authored May 4, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    496a466 View commit details
  3. chore(deps): update dev dependencies (#1789)

    * chore(deps): update dev dependencies
    
    * update node in csb config
    
    * use node 18
    
    * move to dev deps
    
    * fix rollup error
    
    * missing fix
    
    * refactor for general case
    dai-shi authored May 4, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    c4e2809 View commit details
  4. fix: rollup config (#1790)

    dai-shi authored May 4, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    faccbd0 View commit details
  5. 4.3.8

    dai-shi committed May 4, 2023
    Copy the full SHA
    0784028 View commit details
Showing with 3,015 additions and 3,549 deletions.
  1. +1 −1 .codesandbox/ci.json
  2. +9 −10 .eslintrc.json
  3. +1 −1 .github/workflows/lint-and-type.yml
  4. +34 −6 .github/workflows/test-multiple-builds.yml
  5. +24 −6 .github/workflows/test-multiple-versions.yml
  6. +4 −2 .github/workflows/test-old-typescript.yml
  7. +4 −0 docs/getting-started/comparison.md
  8. +1 −1 docs/getting-started/introduction.md
  9. +1 −1 docs/guides/practice-with-no-store-actions.md
  10. +24 −21 docs/guides/{testing.mdx → testing.md}
  11. +4 −4 docs/guides/typescript.md
  12. +4 −4 docs/integrations/persisting-store-data.md
  13. +4 −5 docs/recipes/recipes.mdx
  14. +2 −0 examples/demo/.eslintignore
  15. +2 −0 examples/demo/package.json
  16. +1 −2 examples/demo/src/App.js
  17. +21 −3 examples/demo/src/components/CodePreview.js
  18. +4 −1 examples/demo/src/components/Details.js
  19. +8 −0 examples/demo/src/components/SnippetLang.js
  20. +0 −18 examples/demo/src/resources/code.js
  21. +17 −0 examples/demo/src/resources/javascript-code.jsx
  22. +22 −0 examples/demo/src/resources/typescript-code.tsx
  23. +42 −10 examples/demo/src/styles.css
  24. +1,262 −1,259 examples/demo/yarn.lock
  25. +30 −67 package.json
  26. +1 −1 readme.md
  27. +8 −21 rollup.config.js
  28. +3 −3 src/index.ts
  29. +5 −5 src/middleware.ts
  30. +1 −1 src/middleware/combine.ts
  31. +5 −1 src/middleware/devtools.ts
  32. +1 −1 src/middleware/immer.ts
  33. +17 −4 src/middleware/persist.ts
  34. +2 −2 src/middleware/redux.ts
  35. +1 −1 src/middleware/subscribeWithSelector.ts
  36. +3 −2 src/react.ts
  37. +4 −4 tests/basic.test.tsx
  38. +2 −2 tests/context.test.tsx
  39. +118 −154 tests/devtools.test.tsx
  40. +1 −1 tests/middlewareTypes.test.tsx
  41. +135 −19 tests/persistAsync.test.tsx
  42. +106 −26 tests/persistSync.test.tsx
  43. +1 −1 tests/shallow.test.tsx
  44. +10 −10 tests/subscribe.test.tsx
  45. +33 −0 tests/test-utils.ts
  46. +1 −1 tests/types.test.tsx
  47. +4 −2 tsconfig.json
  48. +23 −0 vitest.config.ts
  49. +1,004 −1,865 yarn.lock
2 changes: 1 addition & 1 deletion .codesandbox/ci.json
Original file line number Diff line number Diff line change
@@ -9,5 +9,5 @@
"next-js-uo1h0",
"pavlobu-zustand-demo-frutec"
],
"node": "14"
"node": "18"
}
19 changes: 9 additions & 10 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@
"prettier",
"react-hooks",
"import",
"jest"
"vitest"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
@@ -36,6 +36,7 @@
"prefer-const": "error",
"curly": ["warn", "multi-line", "consistent"],
"no-console": "off",
"import/extensions": ["error", "always"],
"import/no-unresolved": ["error", { "commonjs": true, "amd": true }],
"import/export": "error",
"@typescript-eslint/no-duplicate-imports": ["error"],
@@ -47,10 +48,12 @@
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-explicit-any": "off",
"jest/consistent-test-it": [
"vitest/consistent-test-it": [
"error",
{ "fn": "it", "withinDescribe": "it" }
],
"import/namespace": "off",
"import/named": "off",
"import/order": [
"error",
{
@@ -93,12 +96,8 @@
"@typescript-eslint/parser": [".js", ".jsx", ".ts", ".tsx"]
},
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx", ".json"],
"paths": ["src"]
},
"alias": {
"extensions": [".js", ".jsx", ".ts", ".tsx", ".json"],
"extensions": [".js", ".jsx", ".ts", ".tsx"],
"map": [
["^zustand$", "./src/index.ts"],
["zustand", "./src"]
@@ -108,9 +107,9 @@
},
"overrides": [
{
"files": ["src"],
"parserOptions": {
"project": "./tsconfig.json"
"files": ["tests/**/*.ts", "tests/**/*.tsx"],
"rules": {
"import/extensions": ["error", "never"]
}
},
{
2 changes: 1 addition & 1 deletion .github/workflows/lint-and-type.yml
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14'
node-version: '18'
cache: yarn
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- run: yarn install --frozen-lockfile --check-files
40 changes: 34 additions & 6 deletions .github/workflows/test-multiple-builds.yml
Original file line number Diff line number Diff line change
@@ -14,11 +14,27 @@ jobs:
matrix:
build: [cjs, umd] # [cjs, esm, umd, system]
env: [development, production]
devtools-skip:
- CI-MATRIX-NOSKIP
include:
- devtools-skip: CI-MATRIX-[2345]
build: umd
- devtools-skip: CI-MATRIX-[1345]
build: umd
- devtools-skip: CI-MATRIX-[1245]
build: umd
- devtools-skip: CI-MATRIX-[1235]
build: umd
- devtools-skip: CI-MATRIX-[1234]
build: umd
exclude:
- devtools-skip: CI-MATRIX-NOSKIP
build: umd
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14'
node-version: '18'
cache: yarn
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- run: yarn install --frozen-lockfile --check-files
@@ -48,13 +64,25 @@ jobs:
sed -i~ "1s/^/import.meta.env=import.meta.env||{};import.meta.env.MODE='${NODE_ENV}';/" tests/*.tsx
env:
NODE_ENV: ${{ matrix.env }}
- name: Patch for UMD/SystemJS
if: ${{ matrix.build == 'umd' || matrix.build == 'system' }}
- name: Patch for UMD (DEV)
if: ${{ matrix.build == 'umd' && matrix.env == 'development' }}
run: |
sed -i~ "s/<rootDir>\/src\(.*\)\.ts/<rootDir>\/dist\/${BUILD}\1.${NODE_ENV}.js/" package.json
sed -i~ 's/"test:ci":.*,$/"test:ci": "jest",/' package.json
sed -i~ "s/<rootDir>\/src\(.*\)\.ts/<rootDir>\/dist\/umd\1.development.js/" package.json
sed -i~ "s/it('\[${DEVTOOLS_SKIP}\]/it.skip('/" tests/devtools.test.tsx
env:
DEVTOOLS_SKIP: ${{ matrix.devtools-skip }}
- name: Patch for UMD (PRD)
if: ${{ matrix.build == 'umd' && matrix.env == 'production' }}
run: |
sed -i~ "s/<rootDir>\/src\(.*\)\.ts/<rootDir>\/dist\/umd\1.production.js/" package.json
sed -i~ "s/it('\[${DEVTOOLS_SKIP}\]/it.skip('/" tests/devtools.test.tsx
env:
DEVTOOLS_SKIP: ${{ matrix.devtools-skip }}
- name: Patch for SystemJS
if: ${{ matrix.build == 'system' }}
run: |
sed -i~ "s/<rootDir>\/src\(.*\)\.ts/<rootDir>\/dist\/system\1.${NODE_ENV}.js/" package.json
env:
BUILD: ${{ matrix.build }}
NODE_ENV: ${{ matrix.env }}
- name: Test ${{ matrix.build }} ${{ matrix.env }}
run: |
30 changes: 24 additions & 6 deletions .github/workflows/test-multiple-versions.yml
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14'
node-version: '18'
cache: yarn
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- run: yarn install --frozen-lockfile --check-files
@@ -33,13 +33,29 @@ jobs:
- 18.0.0
- 18.1.0
- 18.2.0
- 18.3.0-next-1308e49a6-20230330
- 0.0.0-experimental-1308e49a6-20230330
- 18.3.0-canary-aef7ce554-20230503
- 0.0.0-experimental-aef7ce554-20230503
devtools-skip:
- CI-MATRIX-NOSKIP
include:
- devtools-skip: CI-MATRIX-[2345]
react: 16.8.0
- devtools-skip: CI-MATRIX-[1345]
react: 16.8.0
- devtools-skip: CI-MATRIX-[1245]
react: 16.8.0
- devtools-skip: CI-MATRIX-[1235]
react: 16.8.0
- devtools-skip: CI-MATRIX-[1234]
react: 16.8.0
exclude:
- devtools-skip: CI-MATRIX-NOSKIP
react: 16.8.0
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14'
node-version: '18'
cache: yarn
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- run: yarn install --frozen-lockfile --check-files
@@ -52,8 +68,10 @@ jobs:
sed -i~ '1s/^/import React from "react";/' tests/*.tsx
sed -i~ 's/"jsx": "react-jsx"/"jsx": "react"/' tsconfig.json
sed -i~ 's/import\.meta\.env[?]\.MODE/"DEVELOPMENT".toLowerCase()/' src/*.ts src/*/*.ts
sed -i~ 's/"test:ci":.*,$/"test:ci": "jest",/' package.json
- name: Test ${{ matrix.react }}
sed -i~ "s/it('\[${DEVTOOLS_SKIP}\]/it.skip('/" tests/devtools.test.tsx
env:
DEVTOOLS_SKIP: ${{ matrix.devtools-skip }}
- name: Test ${{ matrix.react }} ${{ matrix.devtools-skip }}
run: |
yarn add -D react@${{ matrix.react }} react-dom@${{ matrix.react }}
yarn test:ci
6 changes: 4 additions & 2 deletions .github/workflows/test-old-typescript.yml
Original file line number Diff line number Diff line change
@@ -13,6 +13,7 @@ jobs:
fail-fast: false
matrix:
typescript:
- 4.9.5
- 4.8.4
- 4.7.4
- 4.6.4
@@ -25,7 +26,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14'
node-version: '18'
cache: yarn
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
- run: yarn install --frozen-lockfile --check-files
@@ -35,6 +36,8 @@ jobs:
sed -i~ 's/\/\/ @ts-expect-error.*\[LATEST-TS-ONLY\]//' tests/*.tsx
sed -i~ 's/"target":/"skipLibCheck":true,"target":/' tsconfig.json
sed -i~ 's/"exactOptionalPropertyTypes": true,//' tsconfig.json
sed -i~ 's/"moduleResolution": "nodenext",/"moduleResolution": "node",/' tsconfig.json
sed -i~ 's/"allowImportingTsExtensions": true,//' tsconfig.json
sed -i~ 's/"zustand": \["\.\/src\/index\.ts"\],/"zustand": [".\/dist\/index.d.ts"],/' tsconfig.json
sed -i~ 's/"zustand\/\*": \["\.\/src\/\*\.ts"\]/"zustand\/*": [".\/dist\/*.d.ts"]/' tsconfig.json
sed -i~ 's/"include": .*/"include": ["src\/types.d.ts", "dist\/**\/*", "tests\/**\/*"],/' tsconfig.json
@@ -43,5 +46,4 @@ jobs:
- name: Test ${{ matrix.typescript }}
run: |
yarn add -D typescript@${{ matrix.typescript }}
rm -r node_modules/parse5
yarn tsc --noEmit
4 changes: 4 additions & 0 deletions docs/getting-started/comparison.md
Original file line number Diff line number Diff line change
@@ -21,6 +21,8 @@ both are based on an immutable state model.
However, Redux requires your app to be wrapped
in context providers; Zustand does not.

**Zustand**

```ts
import { create } from 'zustand'

@@ -74,6 +76,8 @@ const useCountStore = create<State & Actions>((set) => ({
}))
```

**Redux**

```ts
import { createStore } from 'redux'
import { useSelector, useDispatch } from 'react-redux'
2 changes: 1 addition & 1 deletion docs/getting-started/introduction.md
Original file line number Diff line number Diff line change
@@ -23,7 +23,7 @@ It may be the one state manager in the React space that gets all of these right.
You can try a live demo [here](https://codesandbox.io/s/dazzling-moon-itop4).

[zombie child problem]: https://react-redux.js.org/api/hooks#stale-props-and-zombie-children
[React concurrency]: https://github.com/bvaughn/rfcs/blob/useMutableSource/text/0000-use-mutable-source.md
[react concurrency]: https://github.com/bvaughn/rfcs/blob/useMutableSource/text/0000-use-mutable-source.md
[context loss]: https://github.com/facebook/react/issues/13332

## Installation
2 changes: 1 addition & 1 deletion docs/guides/practice-with-no-store-actions.md
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ export const useBoundStore = create((set) => ({
text: 'hello',
inc: () => set((state) => ({ count: state.count + 1 })),
setText: (text) => set({ text }),
})
}))
```

This creates a self-contained store with data and actions together.
45 changes: 24 additions & 21 deletions docs/guides/testing.mdx → docs/guides/testing.md
Original file line number Diff line number Diff line change
@@ -8,9 +8,11 @@ nav: 9

When running tests, the stores are not automatically reset before each test run.

Thus, there can be cases where the state of one test can affect another. To make sure all tests run with a pristine store state, you can mock `zustand` during testing and use the following code to create your store:
Thus, there can be cases where the state of one test can affect another. To make sure all tests run
with a pristine store state, you can mock `zustand` during testing and use the following code to
create your store:

```jsx
```js
import { create as actualCreate } from 'zustand'
// const { create: actualCreate } = jest.requireActual('zustand') // if using jest
import { act } from 'react-dom/test-utils'
@@ -34,13 +36,16 @@ beforeEach(() => {

The way you mock a dependency depends on your test runner/library.

In [jest](https://jestjs.io/), you can create a `__mocks__/zustand.js` and place the code in that file. If your app is using `zustand/vanilla` instead of `zustand`, then you'll have to place the above code in `__mocks__/zustand/vanilla.js`.
In [jest](https://jestjs.io/), you can create a `__mocks__/zustand.js` and place the code in that
file. If your app is using `zustand/vanilla` instead of `zustand`, then you'll have to place the
above code in `__mocks__/zustand/vanilla.js`.

### TypeScript usage

If you are using zustand, as documented in [TypeScript Guide](./typescript.md), use the following code:
If you are using zustand, as documented in [TypeScript Guide](./typescript.md), use the following
code:

```typescript
```ts
import { create as actualCreate, StateCreator } from 'zustand'
// if using Jest:
// import { StateCreator } from 'zustand';
@@ -51,12 +56,14 @@ import { act } from 'react-dom/test-utils'
const storeResetFns = new Set<() => void>()

// when creating a store, we get its initial state, create a reset function and add it in the set
export const create = <S>(createState: StateCreator<S>) => {
const store = actualCreate(createState)
const initialState = store.getState()
storeResetFns.add(() => store.setState(initialState, true))
return store
}
const create =
() =>
<S>(createState: StateCreator<S>) => {
const store = actualCreate(createState)
const initialState = store.getState()
storeResetFns.add(() => store.setState(initialState, true))
return store
}

// Reset all stores after each test run
beforeEach(() => {
@@ -66,7 +73,9 @@ beforeEach(() => {

## Resetting state between tests in **react-native** and **jest**

You should use the following code in the `__mocks__/zustand.js` file (the `__mocks__` directory should be adjacent to node_modules, placed in the same folder as node_modules, unless you configured roots to point to a folder other than the project root [jest docs: mocking node modules](https://jestjs.io/docs/manual-mocks#mocking-node-modules)):
You should use the following code in the `__mocks__/zustand.js` file (the `__mocks__` directory
should be adjacent to node_modules, placed in the same folder as node_modules, unless you
configured roots to point to a folder other than the project root [jest docs: mocking node modules](https://jestjs.io/docs/manual-mocks#mocking-node-modules)):

```js
import { act } from '@testing-library/react-native'
@@ -79,19 +88,13 @@ const storeResetFns = new Set()
export const create = (createState) => {
const store = actualCreate(createState)
const initialState = store.getState()
storeResetFns.add(() => {
store.setState(initialState, true)
})
storeResetFns.add(() => store.setState(initialState, true))
return store
}

// Reset all stores after each test run
beforeEach(async () => {
await act(() =>
storeResetFns.forEach((resetFn) => {
resetFn()
})
)
beforeEach(() => {
act(() => storeResetFns.forEach((resetFn) => resetFn()))
})
```

8 changes: 4 additions & 4 deletions docs/guides/typescript.md
Original file line number Diff line number Diff line change
@@ -428,7 +428,7 @@ function useBearStore<T>(
}
```
You can also make an abstract `createBoundedUseStore` if you create bounded `useStore`s often and want to DRY things up...
You can also make an abstract `createBoundedUseStore` function if you need to create bounded `useStore` hooks often and want to DRY things up...
```ts
import { useStore, StoreApi } from 'zustand'
@@ -445,17 +445,17 @@ const bearStore = createStore<BearState>()((set) => ({
}))

const createBoundedUseStore = ((store) => (selector, equals) =>
useStore(store, selector as any, equals)) as <S extends StoreApi<unknown>>(
useStore(store, selector as never, equals)) as <S extends StoreApi<unknown>>(
store: S
) => {
(): ExtractState<S>
<T>(
selector?: (state: ExtractState<S>) => T,
selector: (state: ExtractState<S>) => T,
equals?: (a: T, b: T) => boolean
): T
}

type ExtractState<S> = S extends { get: () => infer X } ? X : never
type ExtractState<S> = S extends { getState: () => infer X } ? X : never

const useBearStore = createBoundedUseStore(bearStore)
```
Loading