https://github.com/ahabhgk/reunx
🐧 Hooks as store
https://github.com/ahabhgk/reunx
Last synced: 3 months ago
JSON representation
🐧 Hooks as store
- Host: GitHub
- URL: https://github.com/ahabhgk/reunx
- Owner: ahabhgk
- Created: 2019-11-14T15:50:02.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-02-16T05:07:46.000Z (over 5 years ago)
- Last Synced: 2024-04-28T14:02:07.504Z (about 1 year ago)
- Language: JavaScript
- Homepage:
- Size: 169 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# reunx
🐧Hooks as store.
## APIs
> A well-designed library whose APIs must be elegant and simple enough.
This library only exposes three functions: `createX`, `useX`, `combineProviders`.
`createX` is used to create a ‘X’ object, which contain a react context and a provider:
```ts
type X = {
Provider: React.FC
Context: React.Context
}
```the X object can be consumed by useX:
```ts
const CounterX = createX(useCounter) // useCounter is a react hook
const { count, decrement, increment } = useX(CounterX)
```To avoid multiple levels of nesting of providers, you can use `combineProviders` to combine lots of providers as one provider, and use `useX(Xobject)` or `useContext(Xobject.Context)` to get the specific context
```ts
const Provider = combineProviders(CounterX.Provider, TimerX.Provider)
```Full support for TypeScript!
## examples
```jsx
import React, { useState, useEffect, useCallback } from 'react'
import { createX, useX, combineProviders } from '../src/index'const useCounter = (initialState = 0) => {
const [count, setCount] = useState(initialState)
const decrement = useCallback(() => setCount(count - 1), [count])
const increment = useCallback(() => setCount(count + 1), [count])return { count, decrement, increment }
}const useTimer = (initialState = 0) => {
const [time, setTime] = useState(initialState)useEffect(() => {
const timer = setInterval(
() => setTime(t => t + 1),
1000,
)return () => {
clearInterval(timer)
}
})return time
}const CounterX = createX(useCounter)
const TimerX = createX(useTimer)const Counter = () => {
const { count, decrement, increment } = useX(CounterX)return (
count: {count}
+
-
)
}const Timer = () => {
const time = useX(TimerX)return
timer: {time}
}const Provider = combineProviders(CounterX.Provider, TimerX.Provider)
const App = () => (
)
```