BitAboutState
Tiny and powerful React state management library.
100% Idiomatic React.
Install
npm install --save @bit-about/state
Features
- 100% Idiomatic React
- 100% Typescript with state types deduction
- Efficient sub-states selectors
- State on hook
- No centralized state provider
- Tiny - only 100KB
- Just works ™
Usage
import { state } from '@bit-about/state'
// 1️⃣ Create your hook-like state
const [Provider, useBase] = state(() => {
const [alice, setAlice] = React.useState("Alice")
return { alice, setAlice }
})
// 3️⃣ Use the selector hook in component
const Child = () => {
const alice = useBase(state => state.alice)
return <p>{alice}</p>
}
// 2️⃣ Wrap the tree with the Provider
const App = () => (
<Provider>
<Child />
</Provider>
)
State selectors
Choose your own way to select state:
// 👍 Rerender when anything changed
const { alice, bob } = useBase()
// 💪 Rerender when alice changed
const alice = useBase(state => state.alice)
// 🤌 Rerender when alice or bob changed
const [alice, bob] = useBase(state => [state.alice, state.bob])
// or
const { alice, bob } = useBase(
state => ({ alice: state.alice, bob: state.bob })
)
NOTE:
Values in objects and arrays created in selectors are shallow compared.
State props
type HookProps = { alice: string, bob: string }
const [Provider, useBase] = state(
(props: HookProps) => {
const [alice, setAlice] = React.useState(props.alice)
return { alice, setAlice, bob: props.bob }
}
)
const App = () => (
<Provider alice="Alice" bob="Bob">
<Child />
</Provider>
)
💛
React Query
BitAboutState import { useQuery } from 'react-query'
import { fetchFruits } from './fruits.ts'
const [Provider, useFruits] = state(() => {
const { data: fruits } = useQuery('fruits', fetchFruits)
return { fruits }
})
// 🧠 Rerender ONLY when fruits changed (no matter if isLoading changes)
const fruits = useBase(state => state.fruits)
Credits
- Constate - approach main inspiration
- use-context-selector & FluentUI - fancy rerender avoiding tricks and code main inspiration
License
MIT © Maciej Olejnik