Skip to content

Instantly share code, notes, and snippets.

@shqld
Last active May 5, 2019 13:44
Show Gist options
  • Save shqld/d1fc0c0db6a25ddf761e12cfec90ac3e to your computer and use it in GitHub Desktop.
Save shqld/d1fc0c0db6a25ddf761e12cfec90ac3e to your computer and use it in GitHub Desktop.
`useStore` hook for reading global state without binding actions
import { useState, useEffect } from 'preact/hooks'
// or
import { useState, useEffect } from 'react'
import { Store } from 'unistore'
// or
import { Store } from 'redux'
const extract = (state: any, key: any) => {
if (!key) return state
if (Array.isArray(key)) {
return key.reduce((acc, k) => {
acc[k] = state[k]
return acc
}, {})
}
return state[key]
}
type UseStore<K> = {
<T extends keyof K>(key: T): K[T]
<T extends Array<keyof K>>(key: T): Pick<K, T[number]>
(key?: undefined): K
}
export const createUseStore = <K>(store: Store<K>) => {
const useStore: UseStore<K> = <T>(key: T) => {
const [state, set] = useState(extract(store.getState(), key))
useEffect(
() =>
store.subscribe(() => {
set(extract(store.getState(), key))
}),
[]
)
return state
}
return {
useStore,
}
}
@shqld
Copy link
Author

shqld commented May 5, 2019

const a = useStore('a')
const { a, b } = useStore(['a', 'b'])
const { a, b, ...others } = useStore()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment