### Demonstrate Zustand Provider and Custom Hook Usage in React
Source: https://zustand.docs.pmnd.rs/guides/initialize-state-with-props
This example shows a complete application setup using the `BearProvider` wrapper component to initialize the store with props and a `HookConsumer` (presumably `CommonConsumer` from previous examples) that uses the custom `useBearContext` hook.
```javascript
// Provider wrapper & custom hook consumer
function App2() {
return (
)
}
```
--------------------------------
### Install `use-sync-external-store` for Zustand v5
Source: https://zustand.docs.pmnd.rs/migrations/migrating-to-v5
This command shows the necessary installation step for `use-sync-external-store`, which becomes a peer dependency in Zustand v5. This package is required when using `createWithEqualityFn` and `useStoreWithEqualityFn` from `zustand/traditional`.
```bash
npm install use-sync-external-store
```
--------------------------------
### Complete Example: Zustand Store with useStoreWithEqualityFn in React
Source: https://zustand.docs.pmnd.rs/hooks/use-store-with-equality-fn
This comprehensive example combines the creation of a Zustand vanilla store with its consumption in a React component using `useStoreWithEqualityFn`. It includes the store definition, the `MovingDot` component that updates position with `shallow` equality, and the root `App` component. This demonstrates a full, runnable setup for managing and reacting to state changes efficiently in React.
```tsx
import { createStore } from 'zustand'
import { useStoreWithEqualityFn } from 'zustand/traditional'
import { shallow } from 'zustand/shallow'
type PositionStoreState = { position: { x: number; y: number } }
type PositionStoreActions = {
setPosition: (nextPosition: PositionStoreState['position']) => void
}
type PositionStore = PositionStoreState & PositionStoreActions
const positionStore = createStore()((set) => ({
position: { x: 0, y: 0 },
setPosition: (position) => set({ position }),
}))
function MovingDot() {
const position = useStoreWithEqualityFn(
positionStore,
(state) => state.position,
shallow,
)
const setPosition = useStoreWithEqualityFn(
positionStore,
(state) => state.setPosition,
shallow,
)
return (