Inspired by react-redux and redux-zero
A custom Preact hook to wire up components to Unistore.
This package has Preact 10 and Unistore 3.4 as peer dependencies.
npm install @preact-hooks/unistore
or yarn add @preact-hooks/unistore
You can also load it via the unpkg CDN
https://unpkg.com/@preact-hooks/unistore
will download the latest UMD bundle.
To get started wrap your app in a Provider
component to make the store available
throughout the entire component tree.
import { StoreProvider } from '@preact-hooks/unistore'
import createStore from 'unistore';
import devtools from 'unistore/devtools';
const initialStore = {}
const store = (process.env.NODE_ENV === 'production')
? createStore(initialStore)
: devtools(createStore(initialStore))
function App() {
return (
<StoreProvider value={store}>
// ...
</StoreProvider>
)
}
🎉 Now you are ready to start using the hooks listed below in your function components.
const store = useStore()
This hook returns a reference to the same Unistore store that was passed into the StoreProvider
component.
This hook should probably not be used frequently. Prefer useSelector
as your primary choice. However, this may be useful for less common scenarios that do require access to the store.
import { useStore } from '@preact-hooks/unistore'
function MyComponent() {
const store = useStore()
// ...
}
// You can pass in a selector function such as (s) => s.prop
// Or, you can pass in a string such as 'foo,bar' which will return { foo, bar }
const result = useSelector(selector, equalityFn?)
To learn about this hook checkout the amazing docs over at React Redux.
Pay attention to:
There is a convenient equality function called shallowEqual
included. You can use this with
the useSelector
hook if you require it. If you're not sure when you'd need this then click
on the link above titled "Equality Comparisons and Updates".
import shallowEqual from '@preact-hooks/unistore/shallowEqual'
function MyComponent() {
const result = useSelector(selectorFn, shallowEqual)
// ...
}
You could also use something like the Lodash _.isEqual()
utility or
Immutable.js's comparison capabilities. It's up to you how the equality check is performed.
You can also checkout Reselect which is a "selector" library for Redux.
const action = useAction(actionFn)
This hook is used to create Unistore actions. The function passed into the hook is identical to how you would create an action for Unistore, they receive the current state and return a state update.
import { useAction } from '@preact-hooks/unistore'
import { h } from 'preact'
function Counter() {
const increment = useAction(({ count }) => ({ count: count 1 }));
return (<button onClick={increment}>Click me</button>);
}
If your actions are defined in another file then just import it and pass it through.
// ...
import { increment } from 'myActionsFile.js'
function Counter() {
const increment = useAction(increment);
// ...
}