Skip to content

#182 SSR data is shared #375

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 14 commits into from
May 5, 2021
Merged
Show file tree
Hide file tree
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: 14 additions & 0 deletions .size-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -159,5 +159,19 @@
"code": 1147
}
}
},
"context.js": {
"bundled": 814,
"minified": 467,
"gzipped": 282,
"treeshaked": {
"rollup": {
"code": 14,
"import_statements": 14
},
"webpack": {
"code": 998
}
}
}
}
13 changes: 13 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
"types": "./shallow.d.ts",
"module": "./esm/shallow.js",
"default": "./shallow.js"
},
"./context": {
"types": "./context.d.ts",
"module": "./esm/context.js",
"default": "./context.js"
}
},
"sideEffects": false,
Expand All @@ -40,6 +45,7 @@
"build:vanilla": "rollup -c --config-vanilla",
"build:middleware": "rollup -c --config-middleware",
"build:shallow": "rollup -c --config-shallow",
"build:context": "rollup -c --config-context",
"postbuild": "yarn copy",
"eslint": "eslint --fix 'src/**/*.{js,ts,jsx,tsx}'",
"eslint-examples": "eslint --fix 'examples/src/**/*.{js,ts,jsx,tsx}'",
Expand Down Expand Up @@ -92,6 +98,13 @@
},
"homepage": "https://github.com/react-spring/zustand",
"jest": {
"rootDir": ".",
"moduleNameMapper": {
"^zustand$": "<rootDir>/src/index.ts"
},
"modulePathIgnorePatterns": [
"dist"
],
"testRegex": "test.(js|ts|tsx)$",
"coverageDirectory": "./coverage/",
"collectCoverage": true,
Expand Down
31 changes: 31 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,37 @@ const useStore = create(devtools(redux(reducer, initialState)))
devtools takes the store function as its first argument, optionally you can name the store with a second argument: `devtools(store, "MyStore")`, which will be prefixed to your actions.
devtools will only log actions from each separated store unlike in a typical *combined reducers* redux store. See an approach to combining stores https://github.com/pmndrs/zustand/issues/163

## React context

The store created with `create` doesn't require context providers. In some cases, you may want to use contexts for dependncy injection. Because the store is a hook, passing it as a normal context value may violate rules of hooks. To avoid misusage, a special `createContext` is provided.

```jsx
import create from 'zustand'
import createContext from 'zustand/context'

const { Provider, useStore } = createContext()

const store = create(...)

const App = () => (
<Provider initialStore={store}>
...
</Provider>
)

const Component = () => {
const state = useStore()
const slice = useStore(selector)
...
}
```

Optionally, `createContext` accepts `initialState` to infer store types.

```ts
const { Provider, useStore } = createContext(initialState)
```

## TypeScript

```tsx
Expand Down
59 changes: 59 additions & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import {
ReactNode,
createElement,
createContext as reactCreateContext,
useContext,
useRef,
} from 'react'
import { UseStore } from 'zustand'
import { EqualityChecker, State, StateSelector } from './vanilla'

function createContext<TState extends State>(_initialState?: TState) {
const ZustandContext = reactCreateContext<UseStore<TState> | undefined>(
undefined
)

const Provider = ({
initialStore,
children,
}: {
initialStore: UseStore<TState>
children: ReactNode
}) => {
const storeRef = useRef<UseStore<TState>>()

if (!storeRef.current) {
storeRef.current = initialStore
}

return createElement(
ZustandContext.Provider,
{ value: storeRef.current },
children
)
}

const useStore = <StateSlice>(
selector?: StateSelector<TState, StateSlice>,
equalityFn: EqualityChecker<StateSlice> = Object.is
) => {
// ZustandContext value is guaranteed to be stable.
const useProviderStore = useContext(ZustandContext)
if (!useProviderStore) {
throw new Error(
'Seems like you have not used zustand provider as an ancestor.'
)
}
return useProviderStore(
selector as StateSelector<TState, StateSlice>,
equalityFn
)
}

return {
Provider,
useStore,
}
}

export default createContext
92 changes: 92 additions & 0 deletions tests/context.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import React from 'react'
import { cleanup, render } from '@testing-library/react'
import create from '../src/index'
import createContext from '../src/context'

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

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

it('creates and uses context store', async () => {
const { Provider, useStore } = createContext<CounterState>()

const store = create<CounterState>((set) => ({
count: 0,
inc: () => set((state) => ({ count: state.count + 1 })),
}))

function Counter() {
const { count, inc } = useStore()
React.useEffect(inc, [inc])
return <div>count: {count * 1}</div>
}

const { findByText } = render(
<Provider initialStore={store}>
<Counter />
</Provider>
)

await findByText('count: 1')
})

it('uses context store with selectors', async () => {
const { Provider, useStore } = createContext<CounterState>()

const store = create<CounterState>((set) => ({
count: 0,
inc: () => set((state) => ({ count: state.count + 1 })),
}))

function Counter() {
const count = useStore((state) => state.count)
const inc = useStore((state) => state.inc)
React.useEffect(inc, [inc])
return <div>count: {count * 1}</div>
}

const { findByText } = render(
<Provider initialStore={store}>
<Counter />
</Provider>
)

await findByText('count: 1')
})

it('throws error when not using provider', async () => {
console.error = jest.fn()

class ErrorBoundary extends React.Component<{}, { hasError: boolean }> {
constructor(props: {}) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError() {
return { hasError: true }
}
render() {
return this.state.hasError ? <div>errored</div> : this.props.children
}
}

const { useStore } = createContext<CounterState>()
function Component() {
useStore()
return <div>no error</div>
}

const { findByText } = render(
<ErrorBoundary>
<Component />
</ErrorBoundary>
)
await findByText('errored')
})
8 changes: 7 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@
"jsx": "preserve",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"moduleResolution": "node"
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"zustand": [
"./src/index.ts"
]
}
},
"include": [
"src/**/*",
Expand Down