precoil
v0.3.6
Published
A minimal state management library for React.
Downloads
71
Maintainers
Readme
Precoil
A minimal state management library for React.
Features
- Minimalistic API based on hooks
- No context provider needed
- Small bundle size
Try it on CodeSandbox.
Install
npm install precoil
Usage
atom
import { atom } from 'precoil'
const textState = atom()
// textState: Atom<undefined>
const textStateWithDefault = atom('')
// textStateWithDefault: Atom<string>
const textState = atom<string>()
// textState: Atom<string | undefined>
Atom.useState
const textState = atom()
const Input = () => {
const [text, setText] = textState.useState()
return (
<input
value={text ?? ''}
onChange={e => setText(e.currentTarget.value)}
/>
)
}
const UpperCaseInput = () => {
const [text] = textState.useState()
return <p>Uppercase: {text && text.toUpperCase() || ''}</p>
}
Atom.useReducer
const countStore = atom({ count: 0 })
const Counter = () => {
const [state, dispatch] = countStore.useReducer((prevState, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: prevState.count + 1 }
case 'RESET':
return { count: 0 }
default:
return prevState
}
})
return (
<>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>inc</button>
<button onClick={() => dispatch({ type: 'RESET' })}>reset</button>
</>
)
}
const MirrorCounter = () => {
const [state] = countStore.useState()
return <span>{state.count}</span>
}
Atom.subscribe
const countStore = atom({ count: 0 })
const unsubscribe = countStore.subscribe(state => {
console.log(`State has been changed to { count: ${state.count} }`)
})
// At some point
unsubscribe()
Atom.destroy
const countStore = atom({ count: 0 })
// Remove all listeners
countStore.destroy()
License
MIT License © 2021 Exuanbo